Home

Awesome

C++ cubic spline interpolation

cubic C2 spline

This is a lightweight implementation of cubic splines to interpolate points f(x<sub>i</sub>) = y<sub>i</sub> with the following features.

Usage

The library is a header-only file with no external dependencies and can be used like this:

#include <vector>
#include "spline.h"
...
    std::vector<double> X, Y;
    ...
    // default cubic spline (C^2) with natural boundary conditions (f''=0)
    tk::spline s(X,Y);			// X needs to be strictly increasing
    double value=s(1.3);		// interpolated value at 1.3
    double deriv=s.deriv(1,1.3);	// 1st order derivative at 1.3
    std::vector<double> solutions = s.solve(0.0);	// solves s(x)=0.0
    ...

The constructor can take more arguments to define the spline, e.g.:

    // cubic Hermite splines (C^1) with enforced monotonicity and
    // left curvature equal to 0.0 and right slope equal 1.0
    tk::spline s(X,Y,tk::spline::cspline_hermite, true,
                 tk::spline::second_deriv, 0.0,
                 tk::spline::first_deriv, 1.0);

This is identical to (must be called in that order):

    tk::spline s;
    s.set_boundary(tk::spline::second_deriv, 0.0,
                   tk::spline::first_deriv, 1.0);
    s.set_points(X,Y);
    s.make_monotonic();

Spline types

Splines are piecewise polynomial functions to interpolate points (x<sub>i</sub>, y<sub>i</sub>). In particular, cubic splines can be represented as

The following splines are available.

A function to enforce monotonicity is available as well:

References

https://kluge.in-chemnitz.de/opensource/spline/