將積分區間 [a, b] 分成 偶數個 等寬子區間(n 為奇數個點),以二次多項式逐段逼近被積函數:
∫f(x)dx ≈ (h/3)[f₀ + 4f₁ + 2f₂ + 4f₃ + ... + 2f_{n-2} + 4f_{n-1} + f_n]
其中 h = (b-a)/(n-1) 為步長。
from math import sin
def f(x):
return x * sin(x)
def simpson(a, b, h):
"""回傳 [a,b] 上步長 h 的 Simpson 積分近似值"""
n = int((b - a) / h) + 1
if n % 2 == 0: # 需奇數個點
n += 1
h = (b - a) / (n - 1)
# 產生函數值陣列
y = [f(a + i * h) for i in range(n)]
# Simpson 加權求和
total = y[0] + y[-1]
for i in range(1, n-1):
total += 4 * y[i] if i % 2 else 2 * y[i]
return total * h / 3.0
if __name__ == '__main__':
a, b, h = 1.0, 3.0, 0.0625
print("積分近似值:", simpson(a, b, h))
# 解析解: sin(3) - 3cos(3) - (sin(1) - cos(1)) ≈ 1.279...
n 為奇數,重新計算實際步長y = f(np.arange(a, b+h, h)) 一次產生陣列scipy.integrate.quad 內建)| 步長 h | 點數 n | 近似值 | 相對誤差 |
|---|---|---|---|
| 0.5 | 5 | 1.2731 | 0.5% |
| 0.125 | 17 | 1.2792 | 0.02% |
| 0.0625 | 33 | 1.2794 | <0.01% |
Simpson 規則以 O(n) 時間達到 O(h⁴) 精度,適合光滑函數數值積分。教學用手寫實作理解原理;生產環境建議直接呼叫 scipy.integrate.simpson 或 quad。