# Lagrange approximation

by ggeo1
Tags: approximation, lagrange
 P: 63 Hello, i have done the following code in c++ which gives me a result but : 1) I compute the product "prod*=(y-x[i])/(x[k]-x[i])" which has variable "y" inside ,but the result i take is just a number.(i want the result to be for example in this form "p(x)=1.02*x^3+2*x^2..." I can't understand how the program manipulates the variable y which does hasn't a value! 2) I don't know if i have it right.. The exercise is : Find Lagrange's polynomial approximation for y(x)=cos(π x), x ∈−1,1 using 5 points (x = -1, -0.5, 0, 0.5, and 1). My code : using namespace std; const double pi=3.1415; // my function double f(double x){ return (cos(pi*x)); } //function to compute lagrange polynomial double lagrange_polynomial(int N){ //N = degree of polynomial double *x;//hold the values x=new double [N+1]; int i,k; double y; //these points are given x[0]=-1.0; x[1]=-0.5; x[2]=0; x[3]=0.5; x[4]=1.0; //computations for finding lagrange polynomial double sum=0; for (k=0;k<=N;k++){ double prod=1.0; for (i=0;i<=N;i++){ if (i==k) prod=1.0; else if (i!=k){ prod*=(y-x[i])/(x[k]-x[i]); } } sum+=prod*f(x[k]); } return sum; } int main() { double deg,result; cout <<"Give the degree of the polynomial :"<>deg; result=lagrange_polynomial(deg); cout <<"The Lagrange approximation is :"<