NUMERICAL INTEGRATION: TRAPEZOIDAL RULE




#include "stdafx.h"
#include "iostream"
#include "conio.h"
#include "math.h"
using namespace std;

class Integration{
private:
       double A; //Area under the curve
       double xmin, xmax; //limits of integration
       int numberOfPoints;
       double(*f)(double x); //function to be interated
public:
       Integration(double(*F)(double x), double a, double b, int n){
             f = F;
             xmin = a;
             xmax = b;
             numberOfPoints = n;
       }
       double Trapezoidal();
};


double Integration::Trapezoidal()
{
       double dx = (xmax - xmin) / double(numberOfPoints);
       double sum = 0.0;
       double x = xmin + dx;
       for (int i = 1; i< numberOfPoints; i++)
       {
             sum += (*f)(x);
             x += dx;
       }
       A = (*f)(xmin)+(*f)(xmax)+2.0*sum;
       A *= dx / double(2.0);
       return A;
}
double FUN(double x) //User supplied function
{
       return x*sqrt(8.0 - x*x*x);
}
int _tmain(int argc, _TCHAR* argv[])
{
       Integration I(FUN, 0, 2, 8);
       cout << I.Trapezoidal() << endl;
       system("pause");
       return 0;

}
Share on Google Plus