Sunday 29 April 2012

NEWTON'S BACKWARD INTERPOLATION FORMULA

#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
int i,j,n,m;
clrscr();
printf("\t\t!! NEWTON GRAGORY BACKWARD INTERPOLATION FORMULA!!\n");
printf("\t\t\t\t By Biswadip Pal \t\t\n\n");
float x[20],y[20],d[20][20],a,h,u,b,z=1.0,k=0.0;

printf("Enter the no.s of entries i.e n:\n");
scanf("%d",&n);

printf("Enter the value of x.\n");
for(i=0;i<=n-1;i++)
{
scanf("%f",&x[i]);
}

printf("Enter the value of y.\n");
for(i=0;i<=n-1;i++)
{
scanf("%f",&y[i]);
}

for(i=1;i<=n;i++)
{
d[i][0]=y[i]-y[i-1];
}

for(j=1;j<=n-2;j++)
{
for(i=j+1;i<=n-1;i++)
{
d[i][j]=d[i][j-1]-d[i-1][j-1];
}
}

printf("%f %f\n",x[0],y[0]);
for(i=1;i<=n-1;i++)
{
printf("%f %f",x[i],y[i]);
for(j=0;j<=i-1;j++)
{
printf(" %f",d[i][j]);
}
printf("\n");
}

printf("Enter the value of x for which y is required\n");
scanf("%f",&a);
for(i=0;a>x[i];i++)
{
m=i;
}
m++;
h=x[1]-x[0];
u=(a-x[m])/h;
for(i=0;i<=m-1;i++)
{
z*=(u+i)/(i+1);
k+=(z*d[m][i]);
}
b=y[m]+k;
printf("\n The value of y at %f = %f\n",a,b);
return 0;
}

Newton's forward interpolation

#include<stdio.h>
#include<conio.h>
#include<math.h>

int main()
{
clrscr();
printf("\t\t!! NEWTON GRAGORY FORWARD INTERPOLATION FORMULA!!\n");
printf("\t\t\t\t By Biswadip Pal \t\t\n\n");
int i,j,n,m;
float x[20],y[20],d[20][20],a,h,u,b,z=1.0,k=0.0;

printf("Enter the no.s of entries i.e n:\n");
scanf("%d",&n);

printf("Enter the value of x.\n");
for(i=0;i<=n-1;i++)
{
scanf("%f",&x[i]);
}

printf("Enter the value of y.\n");
for(i=0;i<=n-1;i++)
{
scanf("%f",&y[i]);
}

for(i=0;i<=n-1;i++)
{
d[i][0]=y[i+1]-y[i];
}

for(j=1;j<=n-2;j++)
{
for(i=0;i<=n-j-2;i++)
{
d[i][j]=d[i+1][j-1]-d[i][j-1];
}
}

for(i=0;i<=n-1;i++)
{
printf("%f %f",x[i],y[i]);
for(j=0;j<=n-i-2;j++)
{
printf(" %f",d[i][j]);
}
printf("\n");
}

printf("Enter the value of x for which y is required\n");
scanf("%f",&a);
for(i=0;a>x[i];i++)
{
m=i;
}

h=x[1]-x[0];
u=(a-x[m])/h;

for(i=0;i<=n-m-2;i++)
{
z*=(u-i)/(i+1);
k+=(z*d[m][i]);
}
b=y[m]+k;
printf("\n The value of y at %f = %f\n",a,b);
return 0;
}

Bisection method

#include <math.h>
#include<conio.h>
#define ESP 0.000001
#define F(x) tan(x)+1.45*(sin(x))*(sin(x))-1
void main()
{
  int i = 1;
  float x0,x1,x2;
  double f1,f2,f0,t;
  clrscr();
  printf("\nEnter the value of x0: ");
  scanf("%f",&x0);

  printf("\nEnter the value of x1: ");
  scanf("%f",&x1);
  printf("\n__________________________________________________________________\n");
  printf("\niteration\t x0\t       x1\t x2\t   f0\t   f1\t   f2");
  printf("\n___________________________________________________________________\n");
  do
  {
  x2=(x0+x1)/2;
  f0=F(x0);
  f1=F(x1);
  f2=F(x2);
  printf("\n%d %f %f %f %lf %lf %lf", i, x0,x1,x2,f0,f1,f2);
  if(f0*f2<0)
    {
     x1=x2;
    }
    else
    {
     x0=x2;
    }
    i++;
  }while(fabs(f2)>ESP);
printf("\n__________________________________________________________\n");
printf("\n\nApp.root = %.6f",x2);
getch();
}