在Python中集成离散点

时间:2015-08-12 12:05:22

标签: python numpy scipy

我有两个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])

当绘制时看起来像这样 - (在蓝线中) enter image description here 黑线突出显示实际点。我希望在x轴上的两个点(标记为红线)之间进行积分,这两个点不在原始数据集中。目标是在上图中找到灰色阴影区域(两条红线之间)。

我如何在python中执行此操作?使用python SciPy库我可以像这样集成

scipy.integrate.trapz(y,x)

这给了我灰色区域阴影区域enter image description here

但是,如果我在x轴上的点和1.5之间进行积分,那么trapz会将阴影区域设置为灰色 - enter image description here

我如何理解这一点。

PS-线图不能表示为函数,因为原始数组中有许多随机点。

正确方向的任何见解都会有所帮助

1 个答案:

答案 0 :(得分:3)

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