Legendre Polynomial – C PROGRAM

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:
(l+1)P_{l+1}(x)-(2l+1)x P_l (x) + lP_{l-1}(x)=0
We would need two more relations, that is the relations for 0th and 1st order Legendre polynomials:
P_0(x)=1
P_1(x)=x
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 :
P_{l}(x)=((2l-1)x P_{l-1} (x) - (l-1)P_{l-2}(x))/l

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 -1\leq x \leq 1 . 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)'

First 5 Legendre polynomials using recurrence relation

YouTube Tutorial:

Using Series Representation

Using Numerical Integration

References:

http://mathworld.wolfram.com/LegendrePolynomial.html

PhD researcher at Friedrich-Schiller University Jena, Germany. I'm a physicist specializing in theoretical, computational and experimental condensed matter physics. I like to develop Physics related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.



Leave a Reply

Your email address will not be published. Required fields are marked *