Search code examples
pythonnumpypolynomials

how to access numpy legendre polynomial basis functions


I can't figure out how to access the Legendre basis functions L_i(x) with numpy.polynomial.legendre. I can only access weighted sums of them, of the sum c_i L_i where c are constant coefficients. How can I access the underlying basis functions? I must be missing something. I include a simple example of the problem below. I hand-coded the correct polynomials and compare them to what I am accessing with Numpy. Clearly, the weighted sum is not the desired individual basis function. How can I make the top plot match the bottom using numpy's polynomial module?

import numpy as np
import matplotlib.pyplot as plt
f, ax = plt.subplots(2)
x = np.linspace(-1, 1, 1000)
def correct_legs(x, c):
   if c == 0: return(np.ones(len(x)))
   if c == 1: return(x)
   if c == 2: return(0.5 * (3 * x ** 2 - 1))
   if c == 3: return(0.5 * (5 * x ** 3 - 3 * x))
   if c == 4: return((1. / 8.) * (35 * x ** 4 - 30 * x ** 2 + 3))
   if c > 4 or c < 0 or type(c)!=int: return(np.nan)
for order in range(5):
   # Attempt to generate legendre polynomials with numpy
   ax[0].plot(x, np.polynomial.legendre.legval(x, np.ones(order + 1)), label=order)

   # plot propper legendre polynomials
   ax[1].plot(x, correct_legs(x, order))
ax[0].legend()
plt.savefig('simpleExample')

enter image description here


Solution

  • Of course the desired solution depends on how you wish to use the polynomial. For the purpose of 'plotting' you can have a look at the Legendre series class. It can generate basis functions in the desired domain through the Legendre.basis method.

    For plotting it works OK

    import numpy as np
    import matplotlib.pyplot as plt
    
    for order in range(5):
       # Attempt to generate legendre polynomials with numpy
       x, y = np.polynomial.legendre.Legendre.basis(order, [-1, 1]).linspace(100)
       plt.plot(x, y, label=order)
    
    plt.legend()
    plt.plot()
    

    enter image description here