Python:在x中以不均匀的步长积分曲线下面积 [英] Python: integrating area under curve with uneven steps in x
问题描述
我有一个 y 值列表和一个 x 值列表.我想找到由这些点定义的曲线下的面积.对于具有均匀间距的 x 值,我找到了几个解决此问题的方法:
但是当 x 值不均匀分布时,这两种方法都不起作用.
例如:
<预><代码>>>>从 scipy.integrate 导入 simps>>>y = np.array([1,1,1,1])>>>x = np.array([0,5,20,30])>>>辛普斯(y,x)-inf当然,在上面的代码中使用 x = np.array([0,10,20,30]) 返回 30.0,正如预期的那样.
谁能建议一种方法来找到 x 间距不均匀的曲线下的面积?
我只想找一个简单的梯形规则:
将 numpy 导入为 npx = np.array([0,5,20,30])y = np.array([1,1,1,1])s = np.sum((x[1:] - x[:-1]) * (y[1:] + y[:-1])/2)# 和...一样# s = 0.0# 对于范围内的 k(len(x) - 1):# s += (x[k+1] - x[k]) * (y[k+1] + y[k])/2印刷)
30.0
I have a list of y values and a list of x values. I would like to find the area under the curve defined by these points. I have found a couple of solutions to this problem for x values with even spacing:
1) Calculating the area under a curve given a set of coordinates, without knowing the function
2) Using scipy to perform discrete integration of the sample
But neither of these works when the x values are not evenly spaced.
For example:
>>> from scipy.integrate import simps
>>> y = np.array([1,1,1,1])
>>> x = np.array([0,5,20,30])
>>> simps(y,x)
-inf
Of course, using x = np.array([0,10,20,30]) in the above code returns 30.0, as expected.
Can anyone suggest a way to find the area under a curve with uneven x-spacing?
I'd just go for a simple trapezoidal rule:
import numpy as np
x = np.array([0,5,20,30])
y = np.array([1,1,1,1])
s = np.sum((x[1:] - x[:-1]) * (y[1:] + y[:-1]) / 2)
# same as
# s = 0.0
# for k in range(len(x) - 1):
# s += (x[k+1] - x[k]) * (y[k+1] + y[k]) / 2
print(s)
30.0
这篇关于Python:在x中以不均匀的步长积分曲线下面积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!