1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
double f(double x);
double CurveArea(double Tol, double a, double b);
double AbsVal(double Area1, double Area2, double A);
double Trapezoid(double a, double b, int N);
int main()
{
double a, b;
double Tol;
cout << "This is a demonstration of integrating X-cubed + 2" << endl;
cout << "Enter the left and right limits of integration: ";
cin >> a >> b;
cout << "Enter desired error tolerance: ";
cin >> Tol;
cout << "The area is approximately " << CurveArea(Tol, a, b) << endl;
return 0;
}
double f(double x)
{
return (x * x * x) + 2;
}
double AbsVal(double Area, double PrevArea)
{
if(Area - PrevArea <= 0)
return ((Area - PrevArea) * -1);
else
return (Area - PrevArea);
}
double Trapezoid(double a, double b, int N)
{
double h = (b - a) / N;
double Sum = 0.5 * h * (f(a) + f(b));
for (int k = 1; k < N; k++)
Sum = Sum + h * f(a + h*k);
return Sum;
}
double CurveArea(double Tol, double a, double b)
{
double Area = Trapezoid(a, b, 10);
double PreviousArea = Trapezoid(a, b, 5);
if (AbsVal(Area, PreviousArea) > Tol)
{
double divided = (a + b) / 2;
Area = CurveArea(Tol, a, divided) + CurveArea(Tol, divided, b);
}
return Area;
}
|