Python 计算分段线性信号积分的函数

Python function to compute the integral of a piecewise linear signal

我一直在寻找一个 Python 函数来计算分段线性函数的积分,但我还没有找到。这就是我的意思:

我有两个列表 x = [x_1,x_2,x_3,..,x_n]y=[y_1,y_2,y_3,...,y_n];列表 x 是有序的,即 x_1<=x_2<=x_3<=...<=x_n。如果我用 matplotlib 绘制它,我会得到以下信息:

    import matplotlib.pyplot as plt
    import matplotlib.markers
    import numpy as np

    x = np.array([0,1,1.2,2])
    y = np.array([0,5,3,8])
    
    plt.figure(figsize=(6,4),dpi=80)
    plt.plot(x,y,marker='o')
    plt.xlabel('x - axis')
    plt.ylabel('y - axis')
    plt.title('Input piecewise linear signal')
    plt.grid(b = True)
    plt.show()

给定这两个列表,有没有办法计算这个函数的积分?

np.sum(np.diff(x) * (y[:-1] + np.diff(y)/2))

解释:

  • 积分是左右宽度时间平均ys
  • np.diff(x) 计算宽度
  • y[:-1] + np.diff(y)/2 是两个 y 的平均值(左 y 加上差值的一半)
  • 结果我们得到了一个积分数组,现在我们只需将它与np.sum
  • 相加

你可以自己写:

from typing import List

# Compute the area under a graph represented by a set of data points
def integral(x: List, y: List) -> float:
    integral = 0
    for i in range(1, len(x)):

        # Largest and smallest values of y
        min_y = min(y[i], y[i-1])
        max_y = max(y[i], y[i-1])

        # Difference in x, y values between this point and the last
        dx = x[i] - x[i-1]
        dy = max_y - min_y

        # Area between the two data points
        integral += (dx * min_y) + (0.5 * dy * dx)

    return integral

注意:这是假设你的 x, y >= 0