Computational Physics - Department of Physics

(Axel Boer) #1

5.6 An Integration Class 143


// End MPI
MPI_Finalize ();
return0;
}// end of main program


// this function defines the function to integrate
doubleint_function(doublex)
{
doublevalue = 4./(1.+x*x);
returnvalue;
}// end of function to evaluate


// this function defines the trapezoidal rule
doubletrapezoidal_rule(doublea,doubleb,intn,double(func)(double))
{
doubletrapez_sum;
doublefa, fb, x, step;
int j;
step=(b-a)/((double) n);
fa=(
func)(a)/2. ;
fb=(func)(b)/2. ;
trapez_sum=0.;
for(j=1; j <= n-1; j++){
x=j
step+a;
trapez_sum+=(func)(x);
}
trapez_sum=(trapez_sum+fb+fa)
step;
returntrapez_sum;
}// end trapezoidal_rule


An obvious extension of this code is to read from file or screenthe integration variables. One
could also use the program library to call a particular integration method.


5.6 An Integration Class


We end this chapter by presenting the usage of the integral class defined in the program
library. Here we have defined two header files, theFunction.hand theIntegral.hfiles. The
program below uses the classes defined in these header files tocompute the integral
∫ 1
0


exp(x)cos(x).

#include
#include
#include"Function.h"
#include"Integral.h"


using namespacestd;


classExpCos:publicFunction{
public:
// Default constructor
ExpCos(){}
// Overloaded function operator().
// Override the function operator() of the parent class.
double operator()(doublex){

Free download pdf