A calibration table might have measurements at inputs 0, 10 and 30, but an instrument often produces a reading between them. Linear interpolation uses the two adjacent knots rather than a single line fitted over the whole table. Outside the measured range, returning the nearest endpoint can make an unsupported reading look calibrated. This example explicitly rejects it.
Run the calibration fixture
Use Python 3.12 and its standard library. Save as interpolate.py and run python3 interpolate.py without optimization. Provide knots as pairs of input reading and calibrated output, ordered by strictly increasing input. The example assumes numeric values in ordinary engineering ranges.
from bisect import bisect_left
from math import isfinite
class Calibration:
def __init__(self, knots):
self.x, self.y = zip(*knots)
if len(self.x) < 2 or not all(map(isfinite, self.x + self.y)):
raise ValueError("need two or more finite knots")
if any(a >= b for a, b in zip(self.x, self.x[1:])):
raise ValueError("inputs must increase strictly")
def estimate(self, x):
if not isfinite(x) or not self.x[0] <= x <= self.x[-1]:
raise ValueError("outside calibrated range")
j = bisect_left(self.x, x)
if self.x[j] == x:
return self.y[j]
t = (x - self.x[j - 1]) / (self.x[j] - self.x[j - 1])
return (1 - t) * self.y[j - 1] + t * self.y[j]
c = Calibration([(0, 2), (10, 4), (30, 5)])
assert [c.estimate(x) for x in (0, 5, 10, 20, 30)] == [2, 3, 4, 4.5, 5]
for bad in [lambda: c.estimate(31), lambda: c.estimate(float("nan")),
lambda: Calibration([(0, 1), (0, 2)]),
lambda: Calibration([(2, 1), (1, 2)])]:
try:
bad()
except ValueError:
pass
else:
raise AssertionError("invalid calibration accepted")
print(f"reading at 20 = {c.estimate(20):.2f}")Expected output
reading at 20 = 4.50Bisection finds the first knot at or above the target. If the target is a knot, its stored output is returned directly. Otherwise, the fraction t measures the distance across that particular segment. At 20, the bounding inputs are 10 and 30, so both calibrated outputs contribute equally. Lookup is logarithmic after validating the table once.
Handle dirty tables and boundary complaints
Duplicate input knots have no segment width and may represent conflicting measurements. Reject them at configuration time and decide whether repeat readings should be averaged upstream or reviewed separately. A descending or empty table is invalid. Also check that readings and table inputs use the same units. Non-finite values are rejected, but unusually large finite coordinates can still exceed the useful range of floating-point subtraction. Use a suitable scale if your input values approach machine limits.
The calibrated output is an estimate between observations, not a new observation. If the response is curved between knots, collect measurements there rather than adding decimal precision to the display. If migrating to NumPy, note that numpy.interp defaults to endpoint values outside the sample range. Keep explicit range checks if you want this tutorial’s fail-on-outside contract.
References and related reading: Python 3.12 bisection documentation, NumPy interpolation and endpoint policy, and Java Samples data-science tutorials.