繁体   English   中英

使用Numpy创建Legendre公式

[英]Create The Legendre Formula Using Numpy

所以,我试图使用numpy.polynomial.legendre命令来生成P2到Pn多项式公式。 我想输入2,它给我p2 = 1/2 *(-1 +3x**2)或如果输入是3它得到我的P3公式。

这样我可以给x值计算每个Pn并使用我的一些类方法来计算错误以找到根。

我设法使用以下内容制作Plot:

 numpy.polynomial.legendre.legval (x, np.identity(10))

我想你正在寻找功能scipy.special.legendre

#Build the polynomial
>>> import scipy.special as sp
>>> sp.legendre(2)
poly1d([ 1.5,  0. , -0.5])

#Compute on an interval from -1 to 1
>>> sp.legendre(2)(np.linspace(-1,1,10))
array([ 1.        ,  0.40740741, -0.03703704, -0.33333333, -0.48148148,
       -0.48148148, -0.33333333, -0.03703704,  0.40740741,  1.        ])

您也可以使用numpy多项式包执行此操作。

In [1]: from numpy.polynomial import Polynomial, Legendre

In [2]: for i in range(5):
   ...:     p = Legendre.basis(i).convert(kind=Polynomial)
   ...:     print p.coef
   ...: 
[ 1.]
[ 0.  1.]
[-0.5  0.   1.5]
[ 0.  -1.5  0.   2.5]
[ 0.375  0.    -3.75   0.     4.375]

注意,系数从低到高顺序。 但是,没有必要转换为幂级数来计算值,而且更准确的是不能。

In [3]: Legendre.basis(2)(np.linspace(-1,1,10))
Out[3]: 
array([ 1.        ,  0.40740741, -0.03703704, -0.33333333, -0.48148148,
       -0.48148148, -0.33333333, -0.03703704,  0.40740741,  1.        ])

您还可以使用linspace方法从[-1,1]绘制结果。

In [4]: plot(*Legendre.basis(2).linspace())
Out[4]: [<matplotlib.lines.Line2D at 0x30da4d0>]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM