I'm interested in full Python code (with math formulas) with all computations needed to calculate natural Cubic Splines from scratch. If possible, fast (e.g. Numpy-based).
I created this question only to share my code (as answer) that I programmed recently from scratch (based on Wikipedia) when learning cubic splines.
I programmed the following code based on Russian Wikipedia Article, as I see almost the same description and formulas are located in English Article.
To speed-up computation I used both Numpy and Numba.
To check the correctness of code I made tests with comparison to reference implementation of the natural cubic spline of scipy.interpolate.CubicSpline, you can see
np.allclose(...)
assertion in my code that proves my formulas are correct.Also, I did timings:
which shows that my spline-params computation is around
3x
times faster than the Scipy version and usage of spline (computation for givenx
) is the same speed as Scipy.Running code below needs one-time installing following packages
python -m pip install numpy numba scipy timerit
, herescipy
andtimerit
are only needed for testing purposes and not needed for actual algorithm.Code draws plots showing original multi-line and both spline approximation for Scipy and Numba versions, as one can see Scipy and Numba lines are the same (meaning that spline computation is same):
Code:
Try it online!