[英]Principal Value Integration with Python
我正在嘗試將 function 與 python 集成。它有一個奇點,使用 scipy.integrate 我無法獲得令人滿意的結果(我也得到了 IntegrationWarning)。
到目前為止,這是我的代碼。 這是我第一次處理這樣的功能,我有點迷茫。
from scipy.integrate import quad
import numpy as np
def integrand(x):
return -(x * np.sin(2*x)) / (x * np.cos(x) + np.sin(x))
def cauchy_principal_value(f, a, b, singular_point):
integral = quad(f, a, b, points=[a, singular_point, b],limit=1000)
return integral
result = cauchy_principal_value(integrand, 0, np.pi, 2.0287665755744362)
print("Principal Value: ", result[0])
誰能幫我?
一般來說,積分程序在處理奇點時需要一些幫助。
在這里,如果您知道您想要一個主值,請使用weight="cauchy"
告訴它quad
(查找quad
的文檔)。 這是一個快速而骯臟的演示:
In [32]: x0 = brentq(lambda x: x * np.cos(x) + np.sin(x), 1e-2, np.pi)
In [33]: quad(lambda x: -(x * np.sin(2*x)) / (x * np.cos(x) + np.sin(x) * (x - x0)), 1e-4, np.pi, weight='cauchy', wvar=x0)
Out[33]: (-4.14269240855162, 1.4398780224416236e-08)
brentq
)weight="cauchy"
被積函數解釋為f(x)
in f(x) / (x - c)
。 因此,計算展開並重新定義圍繞x0
被積函數。 下面我乘以x - x0
代替。integrand
function 重新定義為零。 在下面,我只是離開了x=0
。scipy.integrate.quad function 是通用積分器,在處理奇點或高振盪函數時可能會遇到困難。 在您的情況下,您正在嘗試將 function 與奇點集成,這可能導致 IntegrationWarning 或不准確的結果。
要處理被積函數中的奇點,您可以使用 Cauchy 主值法。 這是您的代碼的更新版本:
from scipy.integrate import quad
import numpy as np
def integrand(x):
return -(x * np.sin(2*x)) / (x * np.cos(x) + np.sin(x))
def cauchy_principal_value(f, a, b, singular_point, **kwargs):
def wrapped(x):
if x == singular_point:
return np.nan
return f(x)
integral = quad(wrapped, a, b, **kwargs)
return integral
result = cauchy_principal_value(integrand, 0, np.pi, 2.0287665755744362)
print("Principal Value:", result[0])
在更新的代碼中,引入了一個包裝器 function wrapped 來處理奇點。 包裝器 function 為奇異點返回 np.nan 以指示被積函數未在該點定義。 如果需要,**kwargs 參數允許您將額外的 arguments 傳遞給 quad function。
通過使用這種方法,集成應該在不引發 IntegrationWarning 的情況下繼續進行。 讓我知道它是否有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.