Question

So, im trying to use numpy.polynomial.legendre commands to generate the P2 to Pn polynomial formulas. I would like to input 2 and it gives me the p2 = 1/2 *(-1 +3x**2) or if the input is 3 it gets me the P3 formula.

That way I can give x values to calculate each Pn and calculate the error for futher using some of my classes methods to find the roots.

I managed to make the Plot using the:

 numpy.polynomial.legendre.legval (x, np.identity(10))
Was it helpful?

Solution

I think you are looking for the function 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.        ])

OTHER TIPS

You can also do this with the numpy polynomial package.

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]

Note that the coefficients go from low to high order. However, there is no need to do the conversion to a power series to compute the values and it is more accurate not to.

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.        ])

You can also plot the result from [-1, 1] using the linspace method.

In [4]: plot(*Legendre.basis(2).linspace())
Out[4]: [<matplotlib.lines.Line2D at 0x30da4d0>]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top