当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。