當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python SciPy special.roots_legendre用法及代碼示例

本文簡要介紹 python 語言中 scipy.special.roots_legendre 的用法。

用法:

scipy.special.roots_legendre(n, mu=False)#

Gauss-Legendre 正交。

計算 Gauss-Legendre 正交 [GL] 的樣本點和權重。樣本點是 n 次勒讓德多項式 的根。這些樣本點和權重在區間 上與權重函數 正確集成次數為 或更小的多項式。更多詳細信息,請參閱 [AS] 中的 2.2.10。

參數

n int

正交順序

mu 布爾型,可選

如果為 True,則返回權重之和,可選。

返回

x ndarray

采樣點

w ndarray

重量

mu 浮點數

權重之和

參考

[AS]

Milton Abramowitz 和 Irene A. Stegun 合編。帶有公式、圖表和數學表格的數學函數手冊。紐約:多佛,1972 年。

[GL] (1,2)

Gauss-Legendre 正交,維基百科,https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_quadrature

例子

>>> import numpy as np
>>> from scipy.special import roots_legendre, eval_legendre
>>> roots, weights = roots_legendre(9)

roots 保存根,weights 保存Gauss-Legendre 正交的權重。

>>> roots
array([-0.96816024, -0.83603111, -0.61337143, -0.32425342,  0.        ,
        0.32425342,  0.61337143,  0.83603111,  0.96816024])
>>> weights
array([0.08127439, 0.18064816, 0.2606107 , 0.31234708, 0.33023936,
       0.31234708, 0.2606107 , 0.18064816, 0.08127439])

通過評估 roots 處的 9 次勒讓德多項式來驗證我們是否有根。所有值都近似為零:

>>> eval_legendre(9, roots)
array([-8.88178420e-16, -2.22044605e-16,  1.11022302e-16,  1.11022302e-16,
        0.00000000e+00, -5.55111512e-17, -1.94289029e-16,  1.38777878e-16,
       -8.32667268e-17])

在這裏,我們將展示如何使用上述值來估計 f(t) = t + 1/t 的從 1 到 2 的積分,使用 Gauss-Legendre 正交 [GL]。首先定義函數和積分限製。

>>> def f(t):
...    return t + 1/t
...
>>> a = 1
>>> b = 2

我們將使用integral(f(t), t=a, t=b) 來表示 f 從 t=a 到 t=b 的定積分。 roots 中的樣本點來自區間 [-1, 1],因此我們將通過變量的簡單變化來重寫積分:

x = 2/(b - a) * t - (a + b)/(b - a)

與逆:

t = (b - a)/2 * x + (a + 2)/2

然後:

integral(f(t), a, b) =
    (b - a)/2 * integral(f((b-a)/2*x + (a+b)/2), x=-1, x=1)

我們可以用 roots_legendre 返回的值來近似後一個積分。

將上麵計算的根從 [-1, 1] 映射到 [a, b]。

>>> t = (b - a)/2 * roots + (a + b)/2

將積分近似為函數值的加權和。

>>> (b - a)/2 * f(t).dot(weights)
2.1931471805599276

將其與 3/2 + log(2) 的確切結果進行比較:

>>> 1.5 + np.log(2)
2.1931471805599454

相關用法


注:本文由純淨天空篩選整理自scipy.org大神的英文原創作品 scipy.special.roots_legendre。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。