Linear interpolation

Linear interpolation is implemented in GammaLib through the GNodeArray class. This class contains a collection of nodes xi that may be used to describe a functional relation yi=f(xi). The following code illustrates how the GNodeArray class is used (see examples/cpp/interpolate/interpolate.cpp for the source code):

C++

1double x_i[] = {1.0, 4.0, 6.0};
2double y_i[] = {8.0, 7.0, 2.0};
3GNodeArray nodes(3, x_i);
4for (double x = 0; x < 10.0; x += 0.5) {
5    nodes.set_value(x);
6    double y = y_i[nodes.inx_left()]  * nodes.wgt_left() + y_i[nodes.inx_right()] * nodes.wgt_right();
7    std::cout << "x=" << x << " : y=" << y << std::endl;
8}

Python

1x_i   = [1.0, 4.0, 6.0]
2y_i   = [8.0, 7.0, 2.0]
3nodes = gammalib.GNodeArray(x_i)
4for x in range(20):
5    nodes.set_value(x*0.5)
6    y = y_i[nodes.inx_left()]  * nodes.wgt_left() + y_i[nodes.inx_right()] * nodes.wgt_right()
7    print('x=%f : y=%f' % (x, y))

In line 1, the nodes xi at which the function values yi are given are declared, the actual function values yi are declared in line 2. In line 3, a node array is constructed from the node values. Note that the actual function values are not part of the node array, only the node values are in fact used by the GNodeArray class.

In lines 4-8, the function is interpolated at a number of values in the interval [0,10[. In line 5, the x value is set at which the interpolation should be done. The interpolation is then done in line 6 using the formula

y=yileft×wileft+yiright×wiright

where ileft and iright are the node indices that encompass the x value, and wileft and wiright are the weights with which the function values yileft and yiright need to be multiplied to obtain the interpolated value y. Note that

wileft+wiright=1

The method also works for extrapolation. For x<x0, ileft=0 and iright=1, while for x>xilast, ileft=ilast1 and iright=ilast (where ilast is the index of the last node, which is 2 in the example above). The weights are set so that y is extrapolated linearly.

It is obvious that GNodeArray needs at least 2 node values to operate.