2

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

Hiddenguy
  • 547
  • 13
  • 33

1 Answers1

1

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)
James C.
  • 46
  • 5
  • 1
    Thanks, thats well "changed" something, but still I am not sure if it is correct. I have updated my question. – Hiddenguy Oct 24 '18 at 10:58
  • Can't comment on the question, but I can comment here. The output looks okay, but I'm not sure the intent of use. In my response I made it order 9 to make sure I wouldn't get a zero. Do you have a longer explanation of what you want to do? – James C. Oct 24 '18 at 11:03
  • 1
    Hm, I think it is a place for another question. As I said before, I need those derivatives for an equation, so to be honest I have thought it is going to compute some kind of number, which can be implemented into an equation. If I move on with my problem I will tag you to the new question, so you'll have a good insight into the problem. Thank you. – Hiddenguy Oct 24 '18 at 11:08