SciPy - integrate.simpson() 方法



SciPy 的 integrate.simpson() 方法用於使用辛普森法則逼近函式的積分。此法則適用於偶數個區間。

假設有兩個樣本,N(偶數)和 N-1(奇數)。為了處理奇數區間的這種情況,simpson() 方法提供了一個 even 引數來控制它。

語法

以下是 SciPy integrate.simpson() 方法的語法:

simpson(y, x)

引數

此方法接受兩個引數:

  • y:此引數表示簡單的數學運算,例如 sin()、exp() 等。
  • x:使用此引數,我們可以表示以下內容:陣列和內建函式。

返回值

此方法返回浮點值作為結果。

示例 1

以下是一個基本示例,演示了 SciPy integrate.simpson() 方法的使用。

import numpy as np
from scipy import integrate

# 100 sample points between 0 and 10
x = np.linspace(0, 10, 100)  
y = x**2

res_integral = integrate.simpson(y, x)
print("The resultant value is ", res_integral)

輸出

以上程式碼產生以下結果:

The resultant value is  333.333505101692

示例 2

在這裡,我們使用辛普森法則和 50 個取樣點,對從 0 到 pi 區間的 sin(x) 函式進行積分。

import numpy as np
from scipy.integrate import simpson

# 50 sample points between 0 and π
x = np.linspace(0, np.pi, 50)  
y = np.sin(x)

res_integral = simpson(y, x)
print("The resultant value is ", res_integral)

輸出

以上程式碼產生以下結果:

The resultant value is  1.999999483788026

說明:這是一個近似值,非常接近 2,它在處理奇數區間時確定了高精度。

示例 3

下面是另一個使用辛普森法則的程式,它將給定的輸入顯示為列表陣列 (x)。然後它使用 exp(),這有助於設定少量資料點(偶數)。最後,使用辛普森方法獲得結果(近似值)。

import numpy as np
from scipy.integrate import simpson

x = np.array([0, 0.1, 0.4, 0.8, 1.0])
y = np.exp(x)

res_integral = simpson(y, x)
print("The resultant value is ", res_integral)

輸出

以上程式碼產生以下結果:

The resultant value is  1.7173084152992835
scipy_reference.htm
廣告
© . All rights reserved.