Tuesday, February 01, 2011

Interpolation by the method of divided difference



Source code:
#include<stdio.h>
#include<conio.h>
#define max 20

void main()
{
 float table[max][max], xval, yval, product=1;
 int i,j, count;

 printf(" METHOD OF DIVIDED DIFFERENCCE  \n\n");
 printf("\n Enter no. of points:-  ");
 scanf("%d",&count);

 printf("\n Enter x and y values in tabular format - \n ");

 for(i=0; i<=2*count-2; i+=2)
  for(j=0; j<=1; j++)
   scanf("%f",&table[i][j]);

 printf("\n Enter x-value?  ");
 scanf("%f",&xval);

 /* Constructing divided difference table */

 for(j=2; j<=count; j++)
  for(i=j-1; i<=2*count-j-1; i+=2)
  {
   table[i][j]=table[i+1][j-1] - table[i-1][j-1];
   table[i][j]/=(table[i+j-1][0] - table[i-j+1][0]);
  }

 /* Calculation of y-value */

 yval = table[0][1] ;

 for(i=0,j=2; j<=count; j++)
 {

  product*=(xval-table[i][0]);
  yval+=product*table[j-1][j];
  i+=2;

 }

 product*=(xval-table[2*count-2][0]);

 /* printing divided difference table */

  printf("\n DIVIDED DIFFERENCE TABLE  \n\n");

 for(i=0; i<=2*count-2; i++)
 {
  if(i%2==0)
            printf("%2.3f %2.3f",table[i][0], table[i][1]);
  else
            printf("           ");

  for(j=2; j<=count; j++)
            if((j%2==0 && i%2==1) || (j%2==1 && i%2==0))
            {
             if(i>=j-1 && i<2*count-j)
                         printf(" %2.3f",table[i][j]);
            }
            else
             printf("     ");

  printf("\n");

 }

 printf("\n\n At x = %f, y = %f", xval, yval);

}

SAMPLE OUTPUT:

Evaluating the value of y at x = 5.604, using the method of divided difference,
given the following table of values:
 
x
5.600
5.602
5.605
5.607
5.608
y
0.7756
0.7768
0.7787
0.7799
0.7806



No comments:

Post a Comment

Do you think this information useful or was not up to the mark? Comment if you have any advices or suggestions about the post.