How to perform cubic spline interpolation in python?

Short answer:

from scipy import interpolate

def f(x):
    x_points = [ 0, 1, 2, 3, 4, 5]
    y_points = [12,14,22,39,58,77]

    tck = interpolate.splrep(x_points, y_points)
    return interpolate.splev(x, tck)

print(f(1.25))

Long answer:

scipy separates the steps involved in spline interpolation into two operations, most likely for computational efficiency.

  1. The coefficients describing the spline curve are computed,
    using splrep(). splrep returns an array of tuples containing the
    coefficients.

  2. These coefficients are passed into splev() to actually
    evaluate the spline at the desired point x (in this example 1.25).
    x can also be an array. Calling f([1.0, 1.25, 1.5]) returns the
    interpolated points at 1, 1.25, and 1,5, respectively.

This approach is admittedly inconvenient for single evaluations, but since the most common use case is to start with a handful of function evaluation points, then to repeatedly use the spline to find interpolated values, it is usually quite useful in practice.

Leave a Comment