Register to reply

Lagrange approximation

by ggeo1
Tags: approximation, lagrange
Share this thread:
ggeo1
#1
Jul8-11, 10:55 AM
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 :"<<endl;
    cin >>deg;

    result=lagrange_polynomial(deg);

    cout <<"The Lagrange approximation is :"<<endl;
    cout <<"p(x) = "<<result;

    return 0;
}
Phys.Org News Partner Science news on Phys.org
Sapphire talk enlivens guesswork over iPhone 6
Geneticists offer clues to better rice, tomato crops
UConn makes 3-D copies of antique instrument parts

Register to reply

Related Discussions
Math approximation problem Calculus & Beyond Homework 4
Log Approximation Calculus & Beyond Homework 7
What is BCS approximation? Quantum Physics 10
Second approximation General Math 1
Approximation math problem General Math 1