我一直在尋找一個 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()

給定這兩個串列,有沒有辦法計算這個函式的積分?
uj5u.com熱心網友回復:
np.sum(np.diff(x) * (y[:-1] np.diff(y)/2))
解釋:
- 積分是左右
ys 的寬度時間平均值 np.diff(x)計算寬度y[:-1] np.diff(y)/2是兩個ys 的平均值(左邊y加上一半的差異)- 結果我們得到了一個積分陣列,現在我們只需將它與
np.sum
uj5u.com熱心網友回復:
你可以自己寫:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/379825.html
