Pages - Menu

Tuesday, 22 July 2014

Implementation of Simpson one third rule in C.

Here is the code..

// TO IMPLEMENT INTEGRATION BY SIMPSON(1/3) RULE
#include<stdio.h>
float value(float );
void main()
{float a,b,v,z,m,h,*x,*y;
int i,k;

printf( "SIMPSON 1/3 RULE\n");
printf("fx=(1\(1+x^2))\n");
printf("Enter lower,upper limits of integrtion\t");
scanf("%f%f",&a,&b);
printf("\nEnter the no of parts of interval(k)\t");
scanf("%d",&k);
x=(float *)malloc(sizeof(float)*(k+1));
y=(float *)malloc(sizeof(float)*(k+1));
x[0]=a;
y[0]=value(x[0]);
for(i=1;i<=k;i++)
{x[i]=x[i-1]+(float)(b/k);
y[i]= value(x[i]);
}for(i=0;i<=k;i++)
printf("|x=%f,y=%f|\n",*(x+i),*(y+i));
z=0;
h=((b-a)/k);
for(i=1;i<k;)
{z=z+y[i];
i=i+2;
}m=0;
for(i=2;i<k;)
{m=m+y[i];
i=i+2;
}
v=((h/3.0)*(y[0]+y[k]+4*z+2*m));
printf("Value of integration is %f \t",v);
free(x);
free(y);

}
float value(float w)
{return(1/(1+(w*w)));
}
For Turbo C users.
// TO IMPLEMENT INTEGRATION BY SIMPSON(1/3) RULE
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
float value(float );
void main()
{float a,b,v,z,m,h,*x,*y;
int i,k;
clrscr();
printf( "SIMPSON 1/3 RULE\n");
printf("fx=(1\(1+x^2))\n");
printf("Enter lower,upper limits of integrtion\t");
scanf("%f%f",&a,&b);
printf("\nEnter the no of parts of interval(k)\t");
scanf("%d",&k);
x=(float *)malloc(sizeof(float)*(k+1));
y=(float *)malloc(sizeof(float)*(k+1));
x[0]=a;
y[0]=value(x[0]);
for(i=1;i<=k;i++)
{x[i]=x[i-1]+(float)(b/k);
y[i]= value(x[i]);
}for(i=0;i<=k;i++)
printf("|x=%f,y=%f|\n",*(x+i),*(y+i));
z=0;
h=((b-a)/k);
for(i=1;i<k;)
{z=z+y[i];
i=i+2;
}m=0;
for(i=2;i<k;)
{m=m+y[i];
i=i+2;
}
v=((h/3.0)*(y[0]+y[k]+4*z+2*m));
printf("Value of integration is %f \t",v);
free(x);
free(y);
getch();
}
float value(float w)
{return(1/(1+(w*w)));
}

No comments:

Post a Comment