【发布时间】:2021-03-18 22:47:43
【问题描述】:
我希望能够在 Python 中对数组进行数值微分和积分。我知道在 numpy 和 scipy 中有这方面的功能。但是,在集成时,我注意到偏移量。
例如,我从一个初始函数 y=cos(x) 开始。
然后我使用 numpy.gradient 求导数。它按预期工作(绘图为 -sin(x)):
当我将导数与 scipy.cumtrapz 集成时,我希望得到初始函数。但是,有一些偏移量。我意识到 -sin(x) 的积分是 cos(x)+constant,那么 cumtrapz 数值积分不考虑这个常数吗?
我担心的是,如果您有一些任意信号,并且不知道初始/边界条件,那么 cumtrapz 是否会忽略 +constant 项? cumtrapz 有解决方案吗?
我使用的代码如下:
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
x = np.linspace(-2*np.pi, 2*np.pi,100)
y = np.cos(x) #starting function
dydx = np.gradient(y, x) #derivative of function
dydx_int = integrate.cumtrapz(dydx, x, initial = 0) #integral of derivative
fig, ax = plt.subplots()
ax.plot(x, y)
ax.plot(x, dydx)
ax.plot(x, dydx_int)
ax.legend(['y = cos(x)', 'dydx = d/dx(cos(x))', 'y = int(dydx)'])
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.show()
【问题讨论】:
标签: python numpy scipy integration offset