Saturday, August 25, 2007

Lagrangian Interploation, backward difference and divided difference - C program

Lagrangian Interploation, backward difference and divided difference - C program

Lagrangian Interploation

#include <stdio.h>
#include <conio.h>
//#define MAX 20


void main ()
{
float x[20], y[20],sum,prod,a;
int i,j,n;
clrscr ();
printf("Enter the number of table points(less then 20): ");
scanf("%d",&n);
printf("Enter %d pair of values for (x,y)\n",n);
for (i = 0; i < n; i++)
{
printf("Enter the value for x[%d]",i);
scanf("%f",&x[i]);
printf("Enter the value for y[%d]",i);
scanf("%f",&y[i]);
}
printf("Enter the value of x for interpolation: ");
scanf("%f",&a);
sum = 0;
for (i = 0; i < n; i++)
{
prod = 1;
for (j = 0; j < n; j++)
{
if (i != j)
prod *= (a - x[j]) / (x[i] - x[j]);
}
sum += y[i] * prod;
}
printf("Interpolated value = %f",sum);
getch ();
}

Backward difference


#include <stdio.h>
#include <conio.h>
#define MAX 8
void main ()
{
int i,j,k,n;
float y[MAX],d[MAX-1][MAX-1]={0};
clrscr ();
printf("\nEnter the number of table points: ");
scanf("%d",&n);
printf("\nEnter %d value of y\n",n);
for (i=0;i<n;i++)
{
printf("Enter the value for y[%d]: ",i+1);
scanf("%f",&y[i]);
}
for (j=0;j<n;j++)
{
for (i=j+1;i<n;i++)
{
if (j==0)
d[j][i] = y[i]-y[i-1];
else
d[j][i] = d[j-1][i] - d[j-1][i-1];
printf("y[%d] = %f\n",j+1,d[j][i]);
}
}
clrscr ();
printf("\n\t\t\tBACKWARD DIFFERENCE TABLE\n");
for (i=0;i<80;i++)
printf("-");
printf("\n");
printf(" y\t\t");
for (i=0;i<n-1;i++)
printf(" d^%dy \t",i+1);
printf("\n");
for (i=0;i<80;i++)
printf("-");
printf("\n");
for (j=0;j<n;j++)
{
printf(" %6.4f \t",y[j]);
for (i=0;i<n;i++)
{
if (d[i][j] != 0)
printf(" %5.4f \t",d[i][j]);
}
printf("\n");
}
for (i=0;i<80;i++)
printf("=");
printf("\n");
getch ();
}

Divided Difference

#include <stdio.h>
#include <conio.h>
#define MAX 8
void main ()
{
int i,j,k,n;
float x[MAX],y[MAX],d[MAX-1][MAX-1]={0};
clrscr ();
printf("\nEnter the number of table points: ");
scanf("%d",&n);
printf("\nEnter %d value of y\n",n);
for (i=0;i<n;i++)
{
printf("Enter the value for x[%d]: ",i+1);
scanf("%f",&x[i]);
printf("Enter the value for y[%d]: ",i+1);
scanf("%f",&y[i]);
}
for (j=0;j<n;j++)
{
for (i=j+1;i<n-j-1;i++)
{
if (j==0)
d[j][i] = (y[i+1]-y[i])/(x[i+1]-x[i]);
else
d[j][i] = d[j-1][i+1] - d[j-1][i]/(x[j+i+1]-x[i]);
}
}
clrscr ();
printf("\n\t\t\tDIVIDED DIFFERENCE TABLE\n");
for (i=0;i<80;i++)
printf("-");
printf("\n");
printf(" x\t\t y\t\t");
for (i=0;i<n-1;i++)
printf(" d^%dyi \t",i+1);
printf("\n");
for (i=0;i<80;i++)
printf("-");
printf("\n");
for (j=0;j<n;j++)
{
printf(" %6f \t%6f \t",x[j],y[j]);
for (i=0;i<n;i++)
{
if (d[i][j] != 0)
printf(" %5f \t",d[i][j]);
}
printf("\n");
}
for (i=0;i<80;i++)
printf("=");
printf("NOTE: Consider the default values for the blank spaces 0.0000");
printf("\n");
getch ();
}

No comments: