SciPy - integrate.quad() 方法



SciPy integrate.quad() 方法用於執行定積分任務。它通常稱為二次方(兩點集合)。

語法

以下是 SciPy integrate.quad() 方法的語法 −

quad(custom_func, upper_lim, lower_lim)

引數

此方法接受以下引數 −

  • custom_func: 此引數設定用於積分計算的使用者定義函式。
  • upper_lim: 此引數用於設定上限。
  • lower_lim: 此引數用於設定下限。

返回值

此方法返回數字整數或絕對誤差作為結果。

示例 1

以下是展示 SciPy integrate.quad() 方法用法的基本示例。

from scipy import integrate

# define the function
def fun(x):
    return x**2

# Perform the integration
res, err = integrate.quad(fun, 0, 1)

print("The result is ", res)
print("The estimated error is ", err)

輸出

以上程式碼生成以下輸出 −

The result is  0.33333333333333337
The estimated error is  3.700743415417189e-15

示例 2

此程式定義了函式 f(x) = sin(x) 在區間 0pi 上的定積分。

import scipy.integrate as sp
import numpy as np

# define the function
def fun(x):
    return np.sin(x)

# perform the integration
res, err = sp.quad(fun, 0, np.pi)

print("The result is ", res)
print("The estimated error is ", err)

輸出

以上程式碼生成以下輸出 −

The result is  2.0
The estimated error is  2.220446049250313e-14

示例 3

在這裡,我們在使用者定義函式中展示指數函式(e-x2),並使用 quad() 執行結果整合。此處,範圍區間在 -infinf 之間設定。

import scipy.integrate as sp
import numpy as np

# define the function
def fun(x):
    return np.exp(-x**2)

# Perform the integration
res, err = sp.quad(fun, -np.inf, np.inf)

print("The result is ", res)
print("The estimated error is ", err)

輸出

以上程式碼生成以下輸出 −

The result is  1.7724538509055159
The estimated error is  1.4202636780944923e-08
scipy_reference.htm
廣告
© . All rights reserved.