C++ Program to evaluate an Definite Integral by Trapezoidal Rule

#include<iostream>  //Header file for cin & cout
#include<cmath>  //Header file for mathematical operartions
using namespace std;  //calling the standard directory

//Taking a function f(x)
float f(float(x))
{
return (pow(x,3)+pow(x,2)-(4*x)-5);
}

//Taking diffrentiation of f(x) i.e. g(x)
float g(float(x))
{
return (3*pow(x,2)+2*x-4);
}

//Taking double diffrentiation of f(x) i.e. h(x)
float h(float(x))
{
return (6*x+4);
}

int main()  //Main Program
{
long double a,b,d,i,n,I=0,J=0,A,K=0,E=0;
cout<<" Given f(x)= x^3 + 2x^2 - 4x - 5 "<<endl;
cout<<"Enter lower limit "<<endl;
cin>>a;
cout<<"Enter Upper Limit "<<endl;
cin>>b;
cout<<"Enter the number of intervals : "<<endl;
cin>>n;
d=(b-a)/n;


//Steps of solving by Trapezoidal Rule
for(i=0;i<=n;i++)
{
I=I+f(a+(i*d));
}

for(i=1;i<n;i++)
{
J=J+f(a+(i*d));
}
A=(d/2)*(I+J);

//Printing the value of Integral
cout<<"The Value of integral under the enterd limits is : "<<endl;
cout<<A<<endl;

//Finding the mean of intervals
for(i=0;i<=n;i++)
{
K=K+a+(i*d);
}

//Calculating the Total Error
E=-((b-a)*d*d*(h(K/n)/12));

//Printing the Totoal Error
cout<<"The Total Error is : "<<endl;
cout<<E<<endl;

return 0;
}

/*OUTPUT
Given f(x)= x^3 + 2x^2 – 4x – 5
Enter lower limit
0
Enter Upper Limit
5
Enter the number of intervals :
100
The Value of integral under the enterd limits is :
122.934
The Total Error is :
-0.0199479
*/

Note – The following programs are coded for Linux (Knoppix) Operating System. For windows do the following changes

change ‘#include ‘ to ‘#include ‘ & same to all other header files.
Delete ‘using namespace std;’.
At the end of main method type return 0;.
Then save it and run it in Turbo C++ or any other software.

I'm a physicist specializing in theoretical, computational and experimental condensed matter physics. I like to develop Physics related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.



Leave a Reply

Your email address will not be published. Required fields are marked *