Legendre polynomials are a type of orthogonal polynomials which occur often in science and engineering. Hence, their generation is crucial to those fields. There are different ways to evaluate a Legendre polynomial, using generating functions, Rodrigues formula, recurrence relation, Gram-Schmidt orthogonalization etc. One of the easiest and also
one of the most accurate, method is using recurrence relation.
Here we use Bonnet’s recurrence relation of legendre polynomials, i.e, –
It can be implemented using Python by proceeding as follows-
We define Legendre polynomials as a function named P(n, x), where n is called the order of the polynomial and x is the point of evaluation. The base cases are if n is 0, then The value of the polynomial is always 1, and it is x when order is 1. These are the seed values required for the recurrence relation.
For other values of n, the function is recursively defined, directly from the Bonnet’s recurrence. Thus, P(n, x) returns values of the Legendre polynomial, by recursion method (A function effectively defined with other base cases of the same function itself.)
Below is the Python implementation –
The value of the polynomial at given point is: 305.0
We can now also plot the Legendre polynomials (say from 1st order to 4th order) using matplotlib.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.