Updated almost 11 years ago by Knödlseder Jürgen

How to integrate a function?

A one-dimensional function f(x) can be integrated using the GIntegral class. To compute \int_{\rm xmin}^{\rm xmax} f(x) proceed as follows:

Define a class that describes the function f(x)

You need first to define the kernel function f(x) by deriving a class from the base class GFunction. In the following example, we define the function f(x)=ax, where a is a parameter of the function:

class function : public GFunction {
    function(double a) : m_a(a) {}
    double eval(double x) { return m_a*x; }
    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 f(x) for any value of x.

Compute the integral \int_{\rm xmin}^{\rm xmax} f(x)

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);
double xmin = 1.0;
double xmax = 2.0;
result = integral.romb(xmin, xmax);

First, an instance of the function kernel f(x) is created. In this example, we set the parameter a=47. 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 10^{-8} (by default, the precision is 10^{-6}). The we set the integration boundaries, and finally, we compute the integral.

Also available in: PDF HTML TXT