Laguerre Polynomial – C PROGRAM

In this post I’m gonna show you how to calculate Laguerre polynomials using three different techniques: using recurrence relations, series representations, and numerical integration.
The programs will calculate and plot the first few Laguerre polynomials.

Using Recurrence Relation

We will be using the following recurrence relation:
(n+1)L_{n+1}(x)=(2n+1-x) L_n (x) - nL_{n-1}(x)
We would need two more relations, that is the relations for 0th and 1st order Laguerre polynomials:
L_0(x)=1
L_1(x)=-x+1
We will create a program that calculates the values of the Laguerre 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 ‘l0’ and ‘l1’, that contain the definition of respectively.
Then we will create a function ‘ln’ that will use the first two functions and recursion to find the value of Legendre polynomial for different x,n.
NOTE: I am using a slightly modified form of the recurrence relation. To get the form I am using, just replace n by n-1.

CODE:

#include<stdio.h>
#include<math.h>

double l0(double x){
	return 1;
}

double l1(double x){
	return -x+1;
}
//The following is a general functoin that returns the value of the Laguerre Polynomial for any given x and n=0,1,2,3,...
double ln(double x, int n){
	if(n==0){
		return l0(x);
	}
	else if(n==1){
		return l1(x);
	}
	else{
		return ((2*(n-1)+1-x)*ln(x,n-1)-(n-1)*ln(x,n-2))/n;
	}
}
main(){
	//We will create a data-file and store the values of first few Legendre polynomials for -1<x<5
	FILE *fp=NULL;
	//create data-file
	fp=fopen("laguerre1.txt","w");
	double x;
	//write the values of first 5 Lagurre  polynomials to data-file
	for(x=-1;x<=5;x=x+0.1){
		fprintf(fp,"%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",x,ln(x,0),ln(x,1),ln(x,2),ln(x,3),ln(x,4));
	}
}

OUTPUT:

The above program will create a data-file called laguerre1.txt and store the values of the first 5 Legendre polynomials for -1\leq x \leq 5 . 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 './laguerre1.txt' u 1:2 w l t 'L0(x)','' u 1:3 w l t 'L1(x)', '' u 1:4 w l t 'L2(x)', '' u 1:5 w l t 'L3(x)', '' u 1:6 w l t 'L4(x)'

First few Laguerre polynomials using recurrence relation

Using Series Representation

Using Numerical Integration

References:

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

[wpedon id="7041" align="center"]

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.