Linear Interpolation Method Using C++ with Output

To interpolate value of dependent variable y at some point of independent variable x using Linear Interpolation, we take two points i.e. if we need to interpolate y corresponding to x which lies between x0 and x1 then we take two points [x0, y0] and [x1, y1] and constructs Linear Interpolants which is the straight line between these points i.e.

y - y0 = ((y1 - y0)/(x1 - x0)) * (x - x0)

For more detail algorithm of this method, we encourage you to read article Linear Interpolation Method Algorithm. In this article we are going to implement Linear Interpolation using C++ and output is also provided.


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

using namespace std;

int main()
{
 float x0,y0,x1,y1,xp,yp;

 /* Inputs */
 cout<<"Enter first point (x0,y0):"<< endl;
 cin>>x0>>y0;
 cout<<"Enter second point (x1,y1):"<< endl;
 cin>>x1>>y1;
 cout<<"Enter interpolation point: ";
 cin>>xp;

 /* Linear Interpolation */
 yp = y0 + ((y1-y0)/(x1-x0)) * (xp - x0);

 /* Displaying Output */
 cout<<"Interpolated value at "<< xp<<" is "<< yp;

 return 0;
}

Output

Consider we have interpolation problem stated as: "From some observation it is found that pressure recorded at temperature 35°C is 5.6KPa and at 40°C is 7.4 KPa. Later it is required to use pressure at 37°C which is not in observation table. So pressure value at 37°C need to be Interpolated and this can be calculated using above program as:"

Enter first point (x0,y0):
35
5.6
Enter second point (x1,y1):
40
7.4
Enter interpolation point: 38
Interpolated value at 38 is 6.68

Recommended Readings

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