The following code snippet showcases how one would use Eigen's spline module to
fit x^2
and find the first and second derivatives along the spline.
An important note is to remember to scale the derivatives with:
(x - x_min) / (x_max - x_min)
(first derivative)(x - x_min) / (x_max - x_min)^2
(second derivative).
Because when fitting a spline to x^2
, the x
values you feed into the spline
fitter is actually normalized with (x - x_min) / (x_max - x_min)
. So using
the chain rule the first derivative of x^2
would be 2x / (x_max - x_min)
and the second derivative would be 2 / (x_max - x_min)**2
.
g++ -I/usr/include/eigen3 spline_deriv_demo.cpp -o spline_deriv_demo
./spline_deriv_demo
1st deriv at x = 0: 4.52754e-16
1st deriv at x = 1: 2
1st deriv at x = 2: 4
1st deriv at x = 3: 6
1st deriv at x = 4: 8
2nd deriv at x = 0: 2
2nd deriv at x = 1: 2
2nd deriv at x = 2: 2
2nd deriv at x = 3: 2
2nd deriv at x = 4: 2