23

我有两个表格数据数组,x 和 y,我不知道生成数据的函数。我希望能够评估沿 x 轴任意点数据产生的线的积分。

与其将分段函数插值到数据中,然后尝试整合我遇到的麻烦,还有什么我可以使用的东西可以通过评估数组来简单地提供积分吗?

在搜索解决方案时,我看到了对 iPython 和 Pandas 的引用,但我无法找到这些包中有助于完成这项任务的部分。

如果没有办法简单地集成阵列,您能否就处理此任务的最佳方式提供一些建议?

4

2 回答 2

24

Scipy has some nice tools to perform numerical integration.

For example, you can use scipy.integrate.simps to perform simpson's Rule, and you can pass it the following:

scipy.integrate.simps(y, x=None, dx=1, axis=-1, even='avg')

Parameters :
y : array_like Array to be integrated.

x : array_like, optional If given, the points at which y is sampled.

dx : int, optional Spacing of integration points along axis of y. Only used when x is None. Default is 1.

axis : int, optional Axis along which to integrate. Default is the last axis.

even : {‘avg’, ‘first’, ‘str’}, optional

‘avg’ : Average two results:1) use the first N-2 intervals with a trapezoidal rule on the last interval and 2) use the last N-2 intervals with a trapezoidal rule on the first interval.

‘first’ : Use Simpson’s rule for the first N-2 intervals with a trapezoidal rule on the last interval.

‘last’ : Use Simpson’s rule for the last N-2 intervals with a trapezoidal rule on the first interval.

So you can use your two arrays to do numerical integration.

于 2013-07-11T19:48:52.037 回答
15

Scipy has an integration feature that can help you.

If you want to use the cumulative sum of trapezoids for integration, which would probably be best for a series of points.

You can do this:

>>> from scipy import integrate
>>> x = np.linspace(-2, 2, num=20)
>>> y = x
>>> y_int = integrate.cumtrapz(y, x, initial=0)
>>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
>>> plt.show()

This will also plot the data and show it to you graphically. This is the integration call integrate.cumtrapz(y, x, initial=0) where x, and y are your two arrays.

于 2013-07-11T19:49:00.370 回答