Sunday, February 3, 2013

C code - Newton's backward difference interpolation

//Newton's backward interpolation

//By Mahesha MG, MIT

#include <stdio.h>

main()

{

float a[10][10],x[10];

int i,j,fact=1,m;

float xm,p,psum,inter;

clrscr();

printf ("enter number of data points: ");

scanf ("%d", &m);

for (i=0; i<m; i++)

{

for (j=0; j<=m; j++)

{

a[i][j] = 0;

}

}

printf ("\nenter the data (x <space> y)\n");

for (i=0; i<m; i++)

scanf ("%f%f", &x[i],&a[i][0]);

for (j=1; j<m; j++)

{

for (i=1; i<m; i++)

{

if (j<=i)

a[i][j]=a[i][j-1]-a[i-1][j-1];

}

}

 

printf ("\nbackward difference table\n");

for (i=0; i<m; i++)

{

printf("%.3f", x[i]);

for (j=0; j<=i; j++)

{

printf ("\t%.3f", a[i][j]);

}

 

printf ("\n");

}

printf ("\nenter x: ");

scanf ("%f", &xm);

p=(xm-x[m-1])/(x[1]-x[0]);

inter=a[m-1][0]+(p*a[m-1][1]);

printf ("\n");

psum=p;

for(i=2; i<m; i++)

{

psum=psum*(p+i-1);

fact=fact*i;

inter=inter+((psum*a[m-1][i])/fact);

}

printf("y value at x= %.3f is %.3f", xm,inter);

}

No comments:

Post a Comment