如何正确使用cumtrapz?

计算科学 Python scipy 一体化 绘图
2021-12-01 15:03:44

我试图用 f(x)=x^2 进行空中飞人积分,我知道反导数的样子,所以 F(x) = (1/3)x^3

这是我的代码,就像我尝试过的一样:

x = np.arange(-10,10, 0.01)   # start,stop,step
f = x**2

l=it.cumtrapz(f,x, initial=0)

plt.plot(l)

然后我得到这个情节(1):

在此处输入图像描述

但情节应该是这样的(2)。轴指定不同,坐标原点 (0,0) 的交点与 (1) 中的不同。:

在此处输入图像描述

如何使用我的代码使 (1) 中的图形看起来与 (2) 完全一样?

1个回答

除非您添加一个常数并使用给定的 x 坐标绘图,否则您正在用它逼近一个定积分cumtrapz不会给您相同的结果作为积分方程:

import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as it

x = np.arange(-10,10, 0.01)   # start,stop,step
f = x**2

f_int=it.cumtrapz(f,x, initial=0)
plt.plot(x, (1/3) * np.power(x,3))                                                                                                                       
plt.plot(x, f_int + (1/3) * np.power(-10,3), '--')                                                                                                       
plt.legend(["(1/3) x^3", "cumtrapz(x^2) + C"])