使用Numpy创建勒让德公式
我正在尝试使用numpy.polynomial.legendre命令来生成从P2到Pn的多项式公式。比如说,我输入2,它就会给我
p2 = 1/2 *(-1 + 3x**2)
,如果输入3,它就会给我P3的公式。这样我就可以给x值来计算每个Pn,并计算误差,之后再用我一些类的方法来找出根。
我已经成功绘制了图形,使用的是:
numpy.polynomial.legendre.legval (x, np.identity(10))
2 个回答
3
你也可以使用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>]
6
我觉得你在找这个函数: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. ])