text: Lagrange 's Interpolation | C ++ program for implementation of Lagrange 's Interpolation ; To represent a data point corresponding to x and y = f ( x ) ; function to interpolate the given data points using Lagrange 's formula xi corresponds to the new data point whose value is to be obtained n represents the number of known data points ; double result = 0 ; Initialize result ; Compute individual terms of above formula ; Add current term to result ; driver function to check the program ; creating an array of 4 known data points ; Using the interpolate function to obtain a data point corresponding to x = 3
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Data { int x , y ; } ; double interpolate ( Data f [ ] , int xi , int n ) { for ( int i = 0 ; i < n ; i ++ ) { double term = f [ i ] . y ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != i ) term = term * ( xi - f [ j ] . x ) / double ( f [ i ] . x - f [ j ] . x ) ; } result += term ; } return result ; } int main ( ) { Data f [ ] = { { 0 , 2 } , { 1 , 3 } , { 2 , 12 } , { 5 , 147 } } ; cout << " Value ▁ of ▁ f ( 3 ) ▁ is ▁ : ▁ " << interpolate ( f , 3 , 5 ) ; return 0 ; }