scipy.cumtrapz和np.trapz给予了不同的答案

gwbalxhn  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(177)

由于某种原因,使用numpy的trapz和scipy的cumtrapz会得到不同的解。

x = np.linspace(-2, 4, num=20)
y = (x)
y_int = integrate.cumtrapz(y, x, initial=0)
y_tr = np.trapz(y, x, axis = 0) 
display(y_tr)
display(y_int)

trapz规则给出的最终值是cumtrapz规则给出的最终值的两倍。

-5.551115123125783e-17
array([ 0.00000000e+00, -3.98891967e-01, -7.53462604e-01, -1.06371191e+00,
       -1.32963989e+00, -1.55124654e+00, -1.72853186e+00, -1.86149584e+00,
       -1.95013850e+00, -1.99445983e+00, -1.99445983e+00, -1.95013850e+00,
       -1.86149584e+00, -1.72853186e+00, -1.55124654e+00, -1.32963989e+00,
       -1.06371191e+00, -7.53462604e-01, -3.98891967e-01, -2.77555756e-16])

有什么原因吗?

cwxwcias

cwxwcias1#

原因似乎是内存分配和执行浮点操作的方式。
-2.77555756e-16-5.551115123125783e-17本质上都是0。通过将极限从-2更改为4来运行相同的代码,可得出正确答案:

x = np.linspace(-2, 4, num=20)
y = (x)
y_int = integrate.cumtrapz(y, x, initial=0)
y_tr = np.trapz(y, x, axis = 0) 
display(y_tr)
display(y_int)

赠送:

6.000000000000001

array([ 0.        , -0.58171745, -1.06371191, -1.44598338, -1.72853186,
       -1.91135734, -1.99445983, -1.97783934, -1.86149584, -1.64542936,
       -1.32963989, -0.91412742, -0.39889197,  0.21606648,  0.93074792,
        1.74515235,  2.65927978,  3.67313019,  4.7867036 ,  6.        ])

在每种情况下,结果都是6。

相关问题