In: Computer Science
Write a computer program using C++ that computes the value of a Lagrange Polynomial and accepts, as input: (n+1) data points (x0, f(x0)), (x1, f(x1)),...(xn, f(xn)).. at value x, which the polynomial is to evaluated. As output, the program should produce a statement that reads, "f(x) = (the value of f(x))". As a test, use the data values (1,2);(-1,1);(0,0);(2,4);(-2,3)
// C++ program that computes the value of a Lagrange Polynomial
#include<bits/stdc++.h>
using namespace std;
int N; //global variable for array size
//interpolation function
// x1 is the new data point whose value is to be evaluated
// n is the no. of known data points
double interpolate(int f[][2], int x1, int n)
{
double result = 0; // Initialize the result with 0
for (int i=0; i<n; i++)
{
// Compute the terms
individually
double term = f[i][1];
for (int k=0;k<n;k++)
{
if (k!=i)
term = term*(x1 - f[k][0])/double(f[i][0] -
f[k][0]);
}
// cumulate terms to find the
result
result += term;
}
return result;
}
// main function
int main()
{
cout<<"Enter size of the input array:";
cin>>N;
int f[N][2];
cout<<"\nEnter data points(as{x,f(x)}):";
for(int i=0;i<N;i++)
cin>>f[i][0]>>f[i][1];
cout<<"\nEnter the value of x: ";
int x;
cin>>x;
cout << "\nValue of f("<<x<<") is :
" << interpolate(f, x, N);
/*call our interpolate function with array,value to be
calculated and number of known values for interpolation*/
return 0;
}
OUTPUT:
Enter size of the input array:5
Enter data points(as{x,f(x)}):
1 2
-1 1
0 0
2 4
-2 3
Enter the value of x: 2
Value of f(2) is : 4