Lagrange Interpolation Method Using C++ with Output

Lagarange method is very suitable for interpolation with unequal intervals. To know detailed algorithm of this method, we suggest you to follow article Lagrange Interpolation Method Algorithm. In this article, we are going to implement Lagarange Interpolation Method using C++ programming language and output of implementation is also provided.

C++ Program for Lagarange Interpolation


#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
	 float x[100], y[100], xp, yp=0, p;
	 int i,j,n;

	 /* Input Section */
	 cout<<"Enter number of data: ";
	 cin>>n;
	 cout<<"Enter data:"<< endl;
	 for(i=1;i<=n;i++)
	 {
		  cout<<"x["<< i<<"] = ";
		  cin>>x[i];
		  cout<<"y["<< i<<"] = ";
		  cin>>y[i];
	 }
	 cout<<"Enter interpolation point: ";
	 cin>>xp;

	 /* Implementing Lagrange Interpolation */
	 for(i=1;i<=n;i++)
	 {
		  p=1;
		  for(j=1;j<=n;j++)
		  {
			   if(i!=j)
			   {
			    	p = p* (xp - x[j])/(x[i] - x[j]);
			   }
		  }
		  yp = yp + p * y[i];
	 }
	 cout<< endl<<"Interpolated value at "<< xp<< " is "<< yp;

	 return 0;
}

Output

Enter number of data: 5
Enter data:
x[1] = 5
y[1] = 150
x[2] = 7
y[2] = 392
x[3] = 11
y[3] = 1452
x[4] = 13
y[4] = 2366
x[5] = 17
y[5] = 5202
Enter interpolation point: 9

Interpolated value at 9 is 810

Recommended Readings

  1. Lagrange Interpolation Method Algorithm
  2. Lagrange Interpolation Method Pseudocode
  3. Lagrange Interpolation Method Using C Programming
  4. Lagrange Interpolation Method Using C++