Pages

This blog is under construction

Tuesday, December 4, 2018

C program to implement Simpson's 1/3 rule

Ex:

Formula:







here a=0, b=6 and h=1


x
0
1
2
3
4
5
6
y=f(x)
1
.50
.33
.25
.20
.16
.14

Now apply Simpson's 1/3 rule:

f(x)= 1/3[(1+.14)+4(.50+.25+.16)+2(.33+.20)]
     =1/3[1.14+1.06+3.64]
     =1/3(5.84)  =1.95


C Code:


#include<stdio.h>
float f(float );

void main()
{ float a,b,h,i,e=0,o=0,fy;
int y=1;
printf("\nEnter the lower and upper limit of a function");
scanf("%f%f",&a,&b);
printf("\nEnter the difference");
scanf("%f",&h);
printf("\nx\t f(x)");
for(i=a;i<=b;i=i+h)
{ printf("\n%f\t%f",i,f(i));
}
for(i=a+h;i<=b-h;i=i+h)
{ if(y%2==0)
e=e+f(i);
else
o=o+f(i);
y++;
}
fy= h/3*(f(a)+f(b)+4*(o)+2*(e));
printf("\nIntegral=%f",fy);

}

float f(float x)
{
return(1/(1+x));
}

Output:

Enter the lower and upper limit of a function
0                                                                                    
6                                                                                                                                               
Enter the difference 1                                                                                                                  
x                 f(x)                                                                                                                
0.000000        1.000000                                                                                                         
1.000000        0.500000                                                                                                         
2.000000        0.333333                                                                                                         
3.000000        0.250000                                                                                                         
4.000000        0.200000                                                                                                         
5.000000        0.166667                                                                                                         
6.000000        0.142857                                                                                                         
Integral=1.958730 

No comments:

Post a Comment