Simson's Rules in c++
Solution in C++:
///******Bismillahir-Rahmanir-Rahim******///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
#include<bits/stdc++.h>
using namespace std;
double givenfuction( double x)
{
double a=1/x;// a=f(x) given funtion
return a;
}
int main()
{
int n,i;
double a,b,dx,sum=0,integral;
cout<<"Enter the limits of integration ,a= ";
cin>>a;
cout<<"Final limit, b=";
cin>>b;
cout<<"Enter the no of subintervals, n= ";
cin>>n;
double x[n+1],y[n+1];
dx=(b-a)/n; // del x value
for (i=0; i<=n; i++)
{
x[i]=a+i*dx; //evaluate x0,x1,x2...xn and store them in x[i] array
y[i]=givenfuction(x[i]); // evaluate y0,y1,y2...yn and also store y[i] array
}
// 4 2 4 pattern equation
// f(x)=dx/3.0(f(x0)+4f(x1)+2f(x2)+4f(x3)+..........f(4*x(n-1)+f(x(n)))
for (i=1; i<n; i+=2)
{
sum=sum+4.0*y[i]; //loop to evaluate 4*(y1+y3+y5+...+yn-1)
}
for (i=2; i<n-1; i+=2)
{
sum=sum+2.0*y[i]; /*loop to evaluate 4*(y1+y3+y5+...+yn-1)+
2*(y2+y4+y6+...+yn-2)*/
}
integral=dx/3.0*(y[0]+y[n]+sum); //h/3*[y0+yn+4*(y1+y3+y5+...+yn-1)+2*(y2+y4+y6+...+yn-2)]
cout<<"The definite integral value is "<<integral<<endl;
return 0;
}
No comments