梯形规则给定列表中的值

Trapezium rule given values in a list

有没有办法对列表中的一组 x 和 y 值执行梯形规则?我有两个数字列表,当它们相互绘制时会给出一个钟形曲线形状,我将如何找到曲线的面积?我有这段代码,但我看不到如何修改它以仅使用两个数字列表;

def trap0 (f ,a ,b ,n ):
    # Basic trapezium rule . Integrate f(x ) over theinterval from a to b using n strips
    h= float (b-a)/n
    s =0.5*(f(a)+f(b))
    for i in range (1,n):
        s= s+f(a+i*h)
    return s*h

您想集成什么功能?是不是例如通过将 x 坐标按顺序排序然后在连续的 (x,y) 对之间线性插值给出的那个?

或者你有一堆可能不规则间隔的 (x,f(x)) 对,你想计算由连续对定义的梯形面积之和(这将是通过这些点的任何函数的积分的近似值)?

如果是前者:我建议遵循这些思路(危险:未经测试的代码):

class PiecewiseLinearFunction:
    def __init__(self, xs, ys):
        self.coords = zip(xs, ys)
        self.coords.sort()
    def __call__(self, x):
        # I'll let you implement this
        # but the idea is to find which interval x lies in, e.g.
        # by bisection, and then to evaluate f by linear interpolation
        # between the ys on either side

之后您可以创建 PiecewiseLinearFunction 的实例并将其传递给您的 trap0 函数或其他任何东西。

如果是后者:对(x,y)对进行排序,可能和上面的代码一样,然后计算每个梯形的面积(宽度乘以平均高度)和加起来。