typestar

Interpolation in Python

Filling in between samples: linear, cubic spline, or a smoothing fit.

import numpy as np
from scipy import interpolate

days = np.array([0, 5, 10, 15, 20])
tpm = np.array([80.0, 88.0, 95.0, 99.0, 104.0])

spline = interpolate.CubicSpline(days, tpm)
print(spline(np.array([2.5, 7.5, 12.5])).round(2))
print(round(float(spline(7.5, 1)), 4),
      round(float(spline.integrate(0, 20)), 2))

linear = interpolate.interp1d(days, tpm, kind="linear")
print(linear(np.array([2.5, 12.5])).round(2))
print(np.interp(2.5, days, tpm).round(2))

How it works

  1. CubicSpline is smooth and passes through every point.
  2. interp1d still covers the simple linear case.
  3. A spline can be differentiated and integrated.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
455
Tokens
166
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 91 seconds.

Type this snippet

Step 2 of 2 in Calculus & interpolation, step 15 of 23 in Scientific computing with SciPy.

← Previous Next →