Lagrange’s Interpolation in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the result for lagranges's interpolation formula.

You don't have write any logic for the program. Just convert the formula into code. Let's see the code.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
struct Data {
   int x, y;
};
double interpolate(Data function[], int xi, int n) {
   double result = 0;
   for (int i = 0; i < n; i++) {
      double term = function[i].y;
      for (int j = 0; j < n; j++) {
         if (j != i) {
            term = term * (xi - function[j].x) / double(function[i].x - function[j].x);
         }
      }
      result += term;
   }
   return result;
}
int main() {
   Data function[] = {{0,3}, {1,2}, {6,9}, {10,17}};
   cout << interpolate(function, 3, 5) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

3

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Updated on 09-Apr-2021 13:16:03

Advertisements