How to calculate and plot Legendre polynomials with python and matplotlib ?

Published: March 10, 2019

DMCA.com Protection Status

To find the Legendre polynomials a solution is to use scipy:

Calculate Legendre polynomials using scipy

>>> from scipy.special import legendre
>>> n = 3
>>> Pn = legendre(n)
>>> Pn(0)
0.0
>>> Pn(0.2)
-0.27999999999999997
>>> Pn(0.5)
-0.43749999999999994
>>>

Calculate on the range [-1,1]:

>>> from scipy.special import legendre
>>> import numpy as np
>>> n = 3
>>> Pn = legendre(n)
>>> x = np.arange(-1,1,0.1)
>>> x
array([ -1.00000000e+00,  -9.00000000e-01,  -8.00000000e-01,
        -7.00000000e-01,  -6.00000000e-01,  -5.00000000e-01,
        -4.00000000e-01,  -3.00000000e-01,  -2.00000000e-01,
        -1.00000000e-01,  -2.22044605e-16,   1.00000000e-01,
         2.00000000e-01,   3.00000000e-01,   4.00000000e-01,
         5.00000000e-01,   6.00000000e-01,   7.00000000e-01,
         8.00000000e-01,   9.00000000e-01])
>>> y = Pn(x)
>>> y
array([ -1.00000000e+00,  -4.72500000e-01,  -8.00000000e-02,
         1.92500000e-01,   3.60000000e-01,   4.37500000e-01,
         4.40000000e-01,   3.82500000e-01,   2.80000000e-01,
         1.47500000e-01,   3.33066907e-16,  -1.47500000e-01,
        -2.80000000e-01,  -3.82500000e-01,  -4.40000000e-01,
        -4.37500000e-01,  -3.60000000e-01,  -1.92500000e-01,
         8.00000000e-02,   4.72500000e-01])

Plot Legendre polynomials using matplolib

How to calculate and plot Legendre polynomials with python and matplotlib ?
How to calculate and plot Legendre polynomials with python and matplotlib ?

from scipy.special import legendre

import matplotlib.pyplot as plt
import numpy as np

min = -1.0
max = 1.0
step = 0.05

for n in range(6):
    Pn = legendre(n)
    x = np.arange(min,max+step,step)
    y = Pn(x)
    plt.plot(x, y)


plt.xlim(-1.0,1.0)
plt.ylim(-1.0,1.01)

plt.savefig('legendre_polynomes.png')
plt.show()

References

Image

of