Nov 18, 2008

Forward Difference Formula

#include

int main()
{
int i,j,n,m;
float x[20],e,y[20],d[20][20],a,h,b1,b2,b3,z,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;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 {
printf(" %3.3f",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];

for(i=0;i< n-m-1;i++)
{
e=i+1;
z=(1/e);
if(i%2!=0) z=-z;
k+=(z*d[m][i]);
}
b1=k/h;
printf(" dy/dx at x=%3.3f =%3.3f\n",a,b1);
k=0;z=0;
for(i=1;i<=n-m;i++)
{
if(i==1){ z=d[m][i];}
if(i==2){ z=-d[m][i];}
if(i==3){ z=0.9166*d[m][i];}
if(i==4){ z=-0.8333*d[m][i];}
k+=z;
}
b2=k/(h*h);
printf("d2y/dx2 at x=%3.3f =%3.3f\n",a,b2);
k=0;z=0;
for(i=2;i<=n-m;i++)
{
if(i==2){z=d[m][i];}
if(i==3){z=-1.5*d[m][i];}
k+=z;
}
b3=k/(h*h*h);
printf("d3y/dx3 at x=%3.3f =%3.3f\n",a,b3);
return 0;
}

0 comments: