Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Lagrange approximation

  1. Jul 8, 2011 #1
    Hello, i have done the following code in c++ which gives me a result but :

    1) I compute the product "prod*=(y-x)/(x[k]-x)" 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 :

    Code (Text):

    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

    //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){

    return sum;

    int main()

        double deg,result;

        cout <<"Give the degree of the polynomial :"<<endl;
        cin >>deg;


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

        return 0;
  2. jcsd
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted