11. Write a program to demonstrate Simpson's 1/3 rule.
/* Program to execte Simpson's 1/3 rule*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
float calc ( float );
void main()
{
float x0,xn,h,y;
int i,sn;
printf("Enter values of x0, xn and number of sub-intervals: ");
scanf("%f%f%d", &x0, &xn, &sn);
if(sn%2==0) {
h=(xn-x0)/sn;
y=calc(x0) + calc(xn);
for(i =1; i < sn; i ++) {
if(i%2==0)
y +=2*calc(x0+i*h);
else
y +=4*calc(x0+i*h);
}
y=(h/3)*y;
printf("Value of integral is %f",y);
getch();
} else
printf("Unsuitable number of intervals");
}
float calc(float x)
{
return 1/(1+x*x);
}
Output
Enter values of x0, xn and number of sub-intervals: 0 6 6
Value of integral is 1.366174