Search code examples
pythonnumpypolynomials

Legendre polynomials derivative


I use this code to create legendre polynomials, from 1st to the 7th order.

N = 4000
xvals = np.linspace(-1, 1, N)

def Legendre(x, n):
    leg = legendre(n)
    P_n = leg(x)
    return P_n

for i in range(1, 8):
    func = Legendre(xvals, i)
    plt.plot(xvals, func, '--', label="n =" + str(i))

It works well, but right now I am struggling with making derivatives from those functions. I decided to switch to numpy to do this, but it is quite poorly described and I stuck with this problem.

Here is the code:

for i in range(1, 8):
    func = np.polynomial.legendre.Legendre.deriv(i)
    print func

UPDATE: Thanks to @James C.

I used his suggestion:

le = np.polynomial.legendre.Legendre((1,2,3,4,5,6,7))

for i in range(1,8):
    print le.deriv(i)

And what I get something like this:

leg([12. 45. 50. 84. 54. 77.])
leg([206. 312. 805. 378. 693.])
leg([ 690. 4494. 1890. 4851.])
leg([ 9345.  5670. 24255.])
leg([ 5670. 72765.])
leg([72765.])
leg([0.])

Unfortunately I am no mathematican, but is it the correct result? I need those derivatives to the equation and at this point I have no idea, how can I put those arrays into.

Libraries: https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.polynomial.legendre.Legendre.deriv.html#numpy.polynomial.legendre.Legendre.deriv


Solution

  • It looks similar to the following:

    Python Unbound Method TypeError

    You want an instance of the class first:

    le = np.polynomial.legendre.Legendre((1,2,3,4,5))
    le.deriv(4)
    

    Just tested:

    import numpy as np
    
    
    for i in range(1, 8):
        le = np.polynomial.legendre.Legendre((1,2,3,4,5,6,7,8,9))
        print le.deriv(i)