Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

evaluating Lagrange polynomial using recursion in python (recursion limit exceeded)

I have the following Lagrange polynomial:
enter image description here

and I am trying to use recursion to solve it, so first I wrote the equation as:

((2*n+1)/(n+1)) * x * P(n,x) – (n/(n+1)) * P(n-1,x)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and I wrote the following function:

def P(n,x):
    if n == 0:
        return 1
    elif n == 1:
        return x
    else:
        return ((2*n+1)/(n+1)) * x * P(n-1,x) - (n/(n+1)) * P(n-1,x)

but I got the following Error:

Traceback (most recent call last):
  File "C:\Users\hp\Desktop\practical work 7\main.py", line 80, in <module>
    print (P(2,2))
  File "C:\Users\hp\Desktop\practical work 7\main.py", line 78, in P
    return ((2*n+1)/n+1) * x * P(n,x) - (n/(n+1)) * P (n-1,x)
  File "C:\Users\hp\Desktop\practical work 7\main.py", line 78, in P
    return ((2*n+1)/n+1) * x * P(n,x) - (n/(n+1)) * P (n-1,x)
  File "C:\Users\hp\Desktop\practical work 7\main.py", line 78, in P
    return ((2*n+1)/n+1) * x * P(n,x) - (n/(n+1)) * P (n-1,x)
  [Previous line repeated 995 more times]
  File "C:\Users\hp\Desktop\practical work 7\main.py", line 73, in P
    if n == 0:
RecursionError: maximum recursion depth exceeded in comparison

I do not want to increase the number of allowed recursions, unless that is the only way to solve the question

I believe that the equation is wrong, since P(n,x) will always call the function and the function will go to the last return again, and it will keep doing that all the time, I just want to know if I missed something or the Question itself is wrong.

>Solution :

Try this:

def P(n, x):
    if n == 0:
        return 1
    if n == 1:
        return x
    return (2 * n - 1) / n * x * P(n - 1, x) - (n - 1) / n * P(n - 2, x)

Examples:

>>> P(2,3)
13.0
>>> P(3,3)
63.0
>>> P(4,3)
321.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading