In this post I’m gonna show you how to calculate Legendre polynomials using three different techniques: using recurrence relations, series representations, and numerical integration.
The programs will calculate and plot the first few Legendre polynomials.
Using Recurrence Relation
We will be using the following recurrence relation:
We would need two more relations, that is the relations for 0th and 1st order Legendre polynomials:
We will create a program that calculates the values of the Legendre polynomial at various x values and for different l and store these values in a txt file. Then just plot it using Gnuplot.
We will create two functions called ‘P0’ and ‘P1’, that contain the definition of respectively.
Then we will create a function ‘Pn’ that will use the first two functions and recursion to find the value of Legendre polynomial for different x,l.
NOTE: I am using a slightly modified form of the recurrence relation. To get the form I am using, just replace l by l-1.
To get :
CODE:
#include<stdio.h> #include<math.h> double P0(double x){ return 1; } double P1(double x){ return x; } //The following is a general functoin that returns the value of the Legendre Polynomial for any given x and n=0,1,2,3,... double Pn(double x, int n){ if(n==0){ return P0(x); }else if(n==1){ return P1(x); }else{ return (double)((2*n-1)*x*Pn(x,n-1)-(n-1)*Pn(x,n-2))/n; } } main(){ //We will create a data-file and store the values of first few Legendre polynomials for -1<x<1 FILE *fp=NULL; //create data-file fp=fopen("legendre1.txt","w"); double x; //write the values of first 5 Legendre polynomials to data-file for(x=-1;x<=1;x=x+0.1){ fprintf(fp,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",x,Pn(x,0),Pn(x,1),Pn(x,2),Pn(x,3),Pn(x,4)); } }
OUTPUT:
The above program will create a data-file called legendre1.txt
and store the values of the first 5 Legendre polynomials for . Now, you can just open the file and select the data and plot it using Excel, GnuPlot, Origin, etc.
For GnuPlot, the command is:
plot './legendre1.txt' u 1:2 w l t 'P0(x)','' u 1:3 w l t 'P1(x)', '' u 1:4 w l t 'P2(x)', '' u 1:5 w l t 'P3(x)', '' u 1:6 w l t 'P4(x)'
YouTube Tutorial:
Using Series Representation
Using Numerical Integration
References:
http://mathworld.wolfram.com/LegendrePolynomial.html
Ph.D. researcher at Friedrich-Schiller University Jena, Germany. I’m a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT, and Machine Learning related apps and software from time to time. Can code in most of the popular languages. I like to share my knowledge in Physics and applications using this Blog and a YouTube channel.