144 5 Numerical Integration
returnexp(x)*cos(x);
}
};
intmain(){
// Declare first an object of the function to be integrated
ExpCos f;
// Set integration bounds
doublea = 0.0; // Lower bound
doubleb = 1.0; // Upper bound
intnpts = 100; // Number of integration points
// Declared (lhs) and instantiate an integral object of typeTrapezoidal
Integraltrapez =newTrapezoidal(a, b, npts, f);
Integralmidpt =newMidPoint(a, b, npts, f);
Integral*gl =newGauss_Legendre(a,b,npts, f);
// Evaluate the integral of the function ExpCos and assign its
// value to the variable result;
doubleresultTP = trapez->evaluate();
doubleresultMP = midpt->evaluate();
doubleresultGL = gl->evaluate();
// Print the result to screen
cout <<"Result with trapezoidal : "<< resultTP << endl;
cout <<"Result with mid-point : "<< resultMP << endl;
cout <<"Result with Gauss-Legendre: "<< resultGL << endl;
}
The header fileFunction.his defined as
http://folk.uio.no/mhjensen/compphys/programs/chapter05/cpp/Function.h
/*
@file Function.h
Interface for mathematical functions with one or more independent variables.
The subclasses are implemented as functors, i.e., objects behaving as functions.
*They overload the function operator().
- Example Usage:
// 1. Declare a functor, i.e., an object which
// overloads the function operator().
class Squared: public Function{
public:
// Overload function operator()
double operator()(double x=0.0){
return xx;
}
};
int main(){
// Instance an object Functor
Squared f;
// Use the instance of the object as a normal function
cout << f(3.0) << endl;
}
@endcode
- **/