Thursday, 13 December 2012

Langrange Interpolation Formula

#include <stdio.h>

#define N 100

int main()
{
    /*
    y=(x-x2)(x-x3)...(x-xn)/(x1-x2)(x1-x3)...(x1-xn)*y[1]
    +(x-x1)(x-x3)...(x-xn)/(x2-x2)(x2-x3)...(x2-xn)*y[2]
    +...+
    (x-x1)(x-x2)...(x-x(n-1))/(xn-x1)(xn-x2)...(xn-x(n-1))*y[n]
    */
    float x[N]={0},y[N]={0};
    int i,j;
    float res,ans=0,givx=0;
    int n=0;
    printf("\nEnter the total number of points for interpolation\n");
    scanf("%d",&n);
    printf("\nEnter the values of x\n");
    for(i=0;i<n;i++)
    scanf("%f",&x[i]);
    printf("\nEnter the values of y\n");
    for(i=0;i<n;i++)
    scanf("%f",&y[i]);
    printf("\nEnter the values of x to find y\n");
    scanf("%f",&givx);
    for(i=0;i<n;i++)
    {
       res=1;
       for(j=0;j<n;j++)
       {
       if(i==j)
        continue;
       res=res*(givx-x[j])/(x[i]-x[j]);
       }
       ans=ans+res*y[i];
    }
    printf("\nanswer = %g\n",ans);
    return 0;
}

No comments: