February 2019

C program for Simpson's 1/3 Rule 


Before Starting the program let us know about the Simpson's 1/3 rule and How it works?
Simpson’s 1/3 Rule The trapezoidal rule was based on approximating the integrand by a first-order polynomial and then integrating the polynomial over an interval of integration. Simpson’s 1/3 rule is an extension of the Trapezoidal rule where the integrand is approximated by a second-order polynomial.





Integration of a function

Simple Simpsons one third Formula


Composite Simpsons one third formula





Application :


  • It is used when it is very difficult to solve the given integral mathematically.
  • This rule gives approximation easily without actually knowing the integration rules


C program to for Composite Simpsons 1/3 rule



#include<stdio.h>
#include<conio.h>
#include<math.h>
//#define f(x) sqrt(1-((x)*(x)))
//#define f(x) exp(-1*(x*x))
//#define f(x) (cos(x)*cos(x))
//#define f(x) sin(x)
#define f(x) exp(-1*(x/2))
int main(){

float a,h,x0,xn,fx0,fxn,term,v;
int i,k;
printf("Composite Simpson's 1/3 rule'");
printf("\nEnter Lower and Upper Limit \n");
scanf("%f%f",&x0,&xn);
printf("\nEnter number of segments (should be multiple of 2)\n");
scanf("%d",&k);
h=(xn-x0)/k;
fx0=f(x0);
fxn=f(xn);
term=f(x0)+f(xn);

for(i=1;i<=(k-1);i=i+2){
a=x0+i*h;
term=term+4*(f(a));
}

for(i=2; i<=(k-2);i=i+2){
a=x0+i*h;
term=term+2*(f(a));
}

v=h/3*term;

printf("\nValue of Integration= %f\n",v);
return 0;
}

C program for Simpsons 1/3 rule

#include<stdio.h>
#include<conio.h>
#include<math.h>
//#define f(x) 3*(x)*(x)+2*(x)-5
//#define f(x) sin(x)
//#define f(x) exp(-1*(x/2))
#define f(x) 3*x*x
int main(){

float h,x0,x1,x2,fx0,fx1,fx2,v;
int n=2;
printf("Simpson's 1/3 rule'");
printf("\nEnter Lower and Upper Limit \n");
scanf("%f%f",&x0,&x2);
h=(x2-x0)/n;
x1=x0+h;
fx0=f(x0);
fx1=f(x1);
fx2=f(x2);
v=h/3*(fx0+4*fx1+fx2);
printf("\nValue of Integration= %f\n",v);
return 0;
}

C programming to calculate value using composite trapezoidal rule

#include<stdio.h>
#include<conio.h>
#include<math.h>
#define F(x) 2*x
int main()
{
int n,i;
float a,b,h,x,sum=0,integral;
printf("Enter the two limits:\n");
scanf("%f%f",&a,&b);
printf("Enter the difference n:\n");
scanf("%d",&n);
h=(b-a)/n;
for(i=1;i<n;i++)
{
x=a+i*h;
sum=sum+F(x);
}
integral=(h/2)*(F(a)+F(b)+2*sum);
printf("\nThe integral is: %f\n",integral);
return 0;
}

C Programming Codes To Compute Value Using Trapezoidal Rule

#include<stdio.h>
#include<conio.h>
#include<math.h>
#define F(x) exp(-(x/2))
int main()
{
int a,b,h;
float i,x,y;
printf("Enter the value for lower and upper limit\n");
scanf("%d%d",&a,&b);
h=b-a;//Calculating height
x=F(a);//Calculation Function and storing in x and y.
y=F(b);
i=h*((x+y)/2);
printf("The Intregrated Value is %.3f",i);
}