Updated about 12 years ago by Knödlseder Jürgen
How to integrate a function?¶
A one-dimensional function can be integrated using the GIntegral
class. To compute proceed as follows:
Define a class that describes the function ¶
You need first to define the kernel function by deriving a class from the base class GFunction
. In the following example, we define the function , where is a parameter of the function:
class function : public GFunction { public: function(double a) : m_a(a) {} double eval(double x) { return m_a*x; } protected: double m_a; //!< A parameter needed by the function };
The class has a constructor (to set the function parameter) and an
eval(x)
method that will be used to evaluate for any value of .
Compute the integral ¶
The numerical integral is then computed using the Romberg integration method provided by the GIntegral
class. The following example illustrates how to proceed:
function f(47.0); GIntegral integral(&f); integral.eps(1.0e-8); double xmin = 1.0; double xmax = 2.0; result = integral.romb(xmin, xmax);
First, an instance of the function kernel is created. In this example, we set the parameter . Then, we declare an integral object which takes a pointer to the function kernel as argument. As third step, we set the relative integration precision to (by default, the precision is ). The we set the integration boundaries, and finally, we compute the integral.