Home > Enterprise >  Python function to compute the integral of a piecewise linear signal
Python function to compute the integral of a piecewise linear signal

Time:12-13

I have been looking for a Python function that allows me to calculate the integral of a piecewise linear function, but I haven't found one yet. This is what I mean:

I have two lists x = [x_1,x_2,x_3,..,x_n] and y=[y_1,y_2,y_3,...,y_n]; the list x is ordered, i.e., x_1<=x_2<=x_3<=...<=x_n. If I graph this with matplotlib I obtain the following:

    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()

enter image description here

Is there a way to compute the integral of this function given this two lists?

CodePudding user response:

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

Explanation:

  • integral is width time average of left and right ys
  • np.diff(x) computes width
  • y[:-1] np.diff(y)/2 is average of two ys (left y plus half the difference)
  • as a result we get an array of piece integrals, now we just sum it with np.sum

CodePudding user response:

You could write your own:

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

Note: this is presuming your x, y >= 0

  • Related