在 Python 中积分离散点
Integrating Discrete point in Python
我有两个 numpy 数组 (x,y)-
import numpy as np
import scipy
from scipy.integrate import simps
y=np.array([1,1,2,1,-2])
x=np.array([0,1,2,3,4])
绘制时看起来像这样 - (蓝线)
黑线突出显示实际点。我希望在不在原始数据集中的 x 轴上的两个点(标记为红线)之间进行积分。目标是找到上图中灰色阴影区域(两条红线之间)。
如何在 python 中执行此操作?使用 python SciPy 库我可以像这样集成
scipy.integrate.trapz(y,x)
这给了我灰色区域中的阴影区域-
但是如果我在 x 轴上的 1.5 和 2.2 点之间进行积分,trapz 给出下面灰色阴影区域 -
我怎样才能得到这个正确的。
PS- 折线图无法表示为函数,因为原始数组中有很多随机点
任何正确方向的见解都会有所帮助
scipy 插值器(例如 InterpolatedUnivariateSpline
)有一个 integral
方法。例如,
In [23]: from scipy.interpolate import InterpolatedUnivariateSpline
In [24]: x = np.array([0, 1, 2, 3, 4])
In [25]: y = np.array([1, 1, 2, 1, -2])
In [26]: f = InterpolatedUnivariateSpline(x, y, k=1) # k=1 gives linear interpolation
In [27]: f.integral(1.5, 2.2)
Out[27]: 1.2550000000000003
我有两个 numpy 数组 (x,y)-
import numpy as np
import scipy
from scipy.integrate import simps
y=np.array([1,1,2,1,-2])
x=np.array([0,1,2,3,4])
绘制时看起来像这样 - (蓝线)
如何在 python 中执行此操作?使用 python SciPy 库我可以像这样集成
scipy.integrate.trapz(y,x)
这给了我灰色区域中的阴影区域-
但是如果我在 x 轴上的 1.5 和 2.2 点之间进行积分,trapz 给出下面灰色阴影区域 -
我怎样才能得到这个正确的。
PS- 折线图无法表示为函数,因为原始数组中有很多随机点
任何正确方向的见解都会有所帮助
scipy 插值器(例如 InterpolatedUnivariateSpline
)有一个 integral
方法。例如,
In [23]: from scipy.interpolate import InterpolatedUnivariateSpline
In [24]: x = np.array([0, 1, 2, 3, 4])
In [25]: y = np.array([1, 1, 2, 1, -2])
In [26]: f = InterpolatedUnivariateSpline(x, y, k=1) # k=1 gives linear interpolation
In [27]: f.integral(1.5, 2.2)
Out[27]: 1.2550000000000003