---
title: Interpolation and lookup tables
heading: Reading between the rows of a table
eyebrow: A4 · Lesson 46 · Interpolation and lookup tables
xp: 40
---

::: hook
A thermistor's datasheet gives its resistance every 5 °C, and your reading falls between two rows. Two data loggers sampled the same test at different moments, and to compare them you need both at the same times. A sensor's calibration is a short table measured on the bench. Lesson 45's fitting finds a smooth model through noisy points; **interpolation** does something different: it trusts the table's points exactly and estimates what lies between them. How you draw the line between two points decides how wrong the answer is.
:::

::: predict
## A 10 kΩ thermistor's table gives 10.000 kΩ at 25 °C and 8.037 kΩ at 30 °C. A straight line between them gives 9.019 kΩ at 27.5 °C. Is the true resistance at 27.5 °C higher or lower?

- [ ] Higher
- [x] Lower
- [ ] Exactly 9.019 kΩ
- [ ] You can't tell from two points

::: reveal
Lower: it's 8.957 kΩ. A thermistor's resistance falls exponentially with temperature, a curve that bends upward (it's convex), so the straight line between two points on it always lies above the curve. The error is 0.7% here, about 0.16 °C. Interpolating the logarithm of the resistance, which is nearly straight, does far better.
:::
:::

::: nameit
## Linear interpolation

Between two table points $(x_0, y_0)$ and $(x_1, y_1)$, the straight line gives

$$y = y_0 + (y_1 - y_0)\,\frac{x - x_0}{x_1 - x_0}$$

`np.interp(x, xp, fp)` does this for a whole table: it finds the interval holding each `x` and applies the formula. Two rules: `xp` must be **increasing**, and outside the table it **clamps**, returning the first or last `fp` instead of extrapolating.

## Interpolate the right quantity

Linear interpolation is exact for data that's linear and nearly exact for data that's nearly linear. So transform first:
- an exponential like a thermistor: interpolate $\ln R$, against $1/T$ for the β model, where the curve becomes a straight line;
- a quantity spanning decades: interpolate its logarithm;
- a filter's response: interpolate decibels against $\log f$.

Then transform back. The table is the same; only the line you draw between its points changes.

## Inverse lookup

To go from a measured resistance back to a temperature, swap the roles: interpolate temperature as a function of resistance. `np.interp` needs the x values increasing, and a thermistor's resistance falls with temperature, so reverse both arrays: `np.interp(R, Rs[::-1], Ts[::-1])`. This only works if the table is monotonic: one temperature for each resistance.

## Resampling

To compare two records sampled at different times, interpolate both onto one common grid of times, then subtract. Resample onto a grid inside both records' time spans, or `np.interp`'s clamping will invent flat ends.

## When to fit instead

Interpolation assumes the table is right. If the points are noisy measurements, interpolating passes through every bit of noise; fit a model instead (lesson 45). And interpolating with one high-degree polynomial through many points is a trap: it wiggles wildly between them near the ends. Piecewise straight lines, or a transformed quantity, are safer.
:::

::: example
## A thermistor table lists $R$ every 5 °C from the β model ($R_{25}$ = 10 kΩ, β = 3950 K). Estimate $R$ at 27.5 °C by interpolating $R$ linearly, then by interpolating $\ln R$ against $1/T$.

::: solution
1. **Build the table and interpolate both ways.** Linearly in $R$, and linearly in $\ln R$ against $1/T$.

```python
import numpy as np
Ts = np.arange(0, 101, 5.0)
Rs = 10e3 * np.exp(3950 * (1 / (Ts + 273.15) - 1 / 298.15))

lin = np.interp(27.5, Ts, Rs)                        # 9018.6
u = 1 / (Ts + 273.15)                                # falls as T rises
lg = np.exp(np.interp(1 / 300.65, u[::-1], np.log(Rs)[::-1]))   # 8956.9
print(lin, lg)
```

2. **The straight line in R.** It gives 9018.6 Ω, 0.69% above the true 8956.9 Ω.
3. **The straight line in ln R against 1/T.** It gives 8956.9 Ω, right to the last digit, because the β model is exactly a straight line in those coordinates.
4. **Why the arrays are reversed.** $1/T$ falls as $T$ rises, and `np.interp` wants increasing x values.

**Answer:** the true value is 8956.9 Ω; interpolating $R$ gives 9018.6 Ω (0.69% high), and interpolating $\ln R$ against $1/T$ gives 8956.9 Ω.
:::
:::

::: example
## The same thermistor reads 9.200 kΩ. Use the 5 °C table to find the temperature, and compare with the exact β-model answer.

::: solution
1. **Look up the resistance in the reversed table.** Resistance falls with temperature, so both arrays are reversed to make the resistances increasing.
2. **Invert the β model for the exact answer.**
   $$\frac{1}{T} = \frac{1}{298.15} + \frac{\ln(R/R_{25})}{\beta}$$

```python
T_est = np.interp(9200, Rs[::-1], Ts[::-1])                # 27.04 °C
T_exact = 1 / (1 / 298.15 + np.log(9200 / 10e3) / 3950) - 273.15   # 26.89 °C
```

3. **Compare.** The table lookup gives 27.04 °C against the exact 26.89 °C: 0.15 °C off, from the same curvature as before.
4. **Improve it.** A finer table or interpolating $\ln R$ would shrink it, and for a firmware lookup table that's usually the trade: a little memory for a lot of accuracy.

**Answer:** the table gives 27.04 °C, 0.15 °C above the exact 26.89 °C.
:::
:::

::: example
## Logger A recorded 1.00, 1.18, 1.42, 1.60, 1.76, 2.04 V at 0, 0.9, 2.1, 3.0, 3.8, 5.2 s. Logger B recorded 1.11, 1.29, 1.52, 1.68, 1.91 V at 0.5, 1.5, 2.5, 3.5, 4.5 s. Compare them at 1, 2, 3 and 4 s.

::: solution
1. **Interpolate both loggers onto a common grid.** Whole seconds from 1 to 4 s, then subtract.

```python
ta = np.array([0, 0.9, 2.1, 3.0, 3.8, 5.2]); va = np.array([1.00, 1.18, 1.42, 1.60, 1.76, 2.04])
tb = np.array([0.5, 1.5, 2.5, 3.5, 4.5]);    vb = np.array([1.11, 1.29, 1.52, 1.68, 1.91])
g = np.arange(1, 5.0)
print(np.interp(g, ta, va) - np.interp(g, tb, vb))   # [0, -0.005, 0, 0.005]
```

2. **Read the grid values.** A reads 1.20, 1.40, 1.60, 1.80 V and B reads 1.20, 1.405, 1.60, 1.795 V.
3. **Why resample.** Neither logger sampled at whole seconds, so without resampling there's no pair of readings taken at the same moment to compare.
4. **Stay inside the data.** The grid stays inside both records (B starts at 0.5 s and ends at 4.5 s).

**Answer:** at 1, 2, 3 and 4 s the loggers differ by 0, −5, 0 and +5 mV, so they agree within 5 mV.
:::
:::

::: check
kind: python
given: k = 1..5 int

## Write `interp(x, xs, ys)` for a single `x` inside the range of an increasing list `xs`: find the interval `xs[i] <= x <= xs[i + 1]` with `bisect.bisect_right`, then apply the straight-line formula. Set `y = [interp(x, xs, ys) for x in queries]` for the starter's table and queries.

```python starter
import bisect, random
random.seed(k)
xs = sorted(random.sample(range(0, 100), 8))
ys = [random.uniform(-5, 5) for _ in xs]
queries = [random.uniform(xs[0], xs[-1]) for _ in range(5)]

def interp(x, xs, ys):
    i = bisect.bisect_right(xs, x) - 1
    return ys[i]

y = [interp(x, xs, ys) for x in queries]
print(y)
```

```python solution
import bisect, random
random.seed(k)
xs = sorted(random.sample(range(0, 100), 8))
ys = [random.uniform(-5, 5) for _ in xs]
queries = [random.uniform(xs[0], xs[-1]) for _ in range(5)]

def interp(x, xs, ys):
    i = bisect.bisect_right(xs, x) - 1
    i = min(max(i, 0), len(xs) - 2)
    x0, x1, y0, y1 = xs[i], xs[i + 1], ys[i], ys[i + 1]
    return y0 + (y1 - y0) * (x - x0) / (x1 - x0)

y = [interp(x, xs, ys) for x in queries]
print(y)
```

```python tests
import numpy as np
assert np.allclose(y, np.interp(queries, xs, ys), rtol=0, atol=1e-12), "Your values should match np.interp: find the interval, then y0 + (y1 - y0)(x - x0)/(x1 - x0)."
assert abs(interp(xs[-1], xs, ys) - ys[-1]) < 1e-12 and abs(interp(xs[0], xs, ys) - ys[0]) < 1e-12, "At the end points the result is the table's own value; keep i within 0 to len(xs) - 2."
```

::: right
Right. `bisect_right` finds the interval in $\log_2 n$ steps, and clamping the index handles a query exactly at the last point, where the interval would otherwise run off the end of the table.
:::
:::

::: check
kind: python
given: T = 12.5 | 27.5 | 41 | 63.7 | 88.2; step = 5 | 10

## Build a β-model thermistor table ($R_{25}$ = 10 kΩ, β = 3950 K) from 0 to 100 °C every `step` = {step} °C. At `T` = {T} °C, set `r_lin` by interpolating $R$ linearly in temperature, `r_log` by interpolating $\ln R$ against $1/T$ (kelvins), and `err_lin`, `err_log` to their errors in percent against the exact value.

```python starter
import numpy as np
Ts = np.arange(0, 101, step)
Rs = 10e3 * np.exp(3950 * (1 / (Ts + 273.15) - 1 / 298.15))
r_lin = np.interp(T, Ts, Rs)
r_log = r_lin
err_lin = err_log = 0
print(r_lin, r_log)
```

```python solution
import numpy as np
Ts = np.arange(0, 101, step)
Rs = 10e3 * np.exp(3950 * (1 / (Ts + 273.15) - 1 / 298.15))
exact = 10e3 * np.exp(3950 * (1 / (T + 273.15) - 1 / 298.15))
r_lin = np.interp(T, Ts, Rs)
u = 1 / (Ts + 273.15)
r_log = np.exp(np.interp(1 / (T + 273.15), u[::-1], np.log(Rs)[::-1]))
err_lin = 100 * (r_lin - exact) / exact
err_log = 100 * (r_log - exact) / exact
print(r_lin, r_log, err_lin, err_log)
```

```python tests
import numpy as np
Ts2 = np.arange(0, 101, step); Rs2 = 10e3 * np.exp(3950 * (1 / (Ts2 + 273.15) - 1 / 298.15))
ex = 10e3 * np.exp(3950 * (1 / (T + 273.15) - 1 / 298.15))
assert abs(r_lin - np.interp(T, Ts2, Rs2)) < 1e-9, "r_lin is np.interp(T, Ts, Rs)."
assert abs(r_log - ex) < 1e-6 * ex, "Interpolating ln R against 1/T is exact for the β model. Reverse the arrays, since 1/T falls as T rises."
assert abs(err_lin - 100 * (r_lin - ex) / ex) < 1e-9 and err_lin > 0, "err_lin is positive: the straight line lies above the convex curve."
assert abs(err_log) < 1e-6, "err_log should be essentially zero."
```

::: right
Right. Linear interpolation in $R$ always reads high on this convex curve, and worse with the coarser table; in the coordinates where the model is a straight line, the error vanishes. Choosing the coordinates is most of the art of interpolation.
:::
:::

::: check
kind: python
given: Rm = 3000 | 6500 | 9200 | 15000 | 27000

## Using a 5 °C table of the same thermistor from 0 to 100 °C, set `T_est` to the temperature for a measured resistance of `Rm` = {Rm} Ω by interpolating temperature against resistance, and `T_exact` from the β model, $T = 1/(1/298.15 + \ln(R/R_{25})/\beta) - 273.15$.

```python starter
import numpy as np
Ts = np.arange(0, 101, 5.0)
Rs = 10e3 * np.exp(3950 * (1 / (Ts + 273.15) - 1 / 298.15))
T_est = np.interp(Rm, Rs, Ts)
T_exact = 0
print(T_est, T_exact)
```

```python solution
import numpy as np
Ts = np.arange(0, 101, 5.0)
Rs = 10e3 * np.exp(3950 * (1 / (Ts + 273.15) - 1 / 298.15))
T_est = np.interp(Rm, Rs[::-1], Ts[::-1])
T_exact = 1 / (1 / 298.15 + np.log(Rm / 10e3) / 3950) - 273.15
print(T_est, T_exact)
```

```python tests
import numpy as np
Ts2 = np.arange(0, 101, 5.0); Rs2 = 10e3 * np.exp(3950 * (1 / (Ts2 + 273.15) - 1 / 298.15))
assert abs(T_est - np.interp(Rm, Rs2[::-1], Ts2[::-1])) < 1e-9, "np.interp needs increasing x values: reverse both arrays, since R falls as T rises."
assert abs(T_exact - (1 / (1 / 298.15 + np.log(Rm / 10e3) / 3950) - 273.15)) < 1e-9, "T_exact is 1/(1/298.15 + ln(R/10k)/3950) - 273.15."
assert abs(T_est - T_exact) < 0.5, "The table lookup should land within half a degree."
```

::: right
Right. Without reversing, `np.interp` silently returns nonsense for a decreasing table, which is the most common bug in thermistor code. The lookup lands within a few tenths of a degree of the exact answer.
:::
:::

::: check
kind: python
given: k = 1..5 int

## The starter gives two loggers' records of the same signal at irregular times, `(ta, va)` and `(tb, vb)`. Resample both onto a grid of whole seconds that lies inside both records, set `g` to that grid, `d` to the differences A minus B on it, and `rms` to the RMS of `d`.

```python starter
import numpy as np
rng = np.random.default_rng(k)
ta = np.sort(rng.uniform(0, 60, 40)); tb = np.sort(rng.uniform(3, 57, 35))
sig = lambda t: 2 + np.sin(2 * np.pi * t / 30)
va = sig(ta) + rng.normal(0, 0.01, ta.size); vb = sig(tb) + 0.02 + rng.normal(0, 0.01, tb.size)
g = np.arange(0, 61.0)
d = np.interp(g, ta, va) - np.interp(g, tb, vb)
rms = 0
print(rms)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
ta = np.sort(rng.uniform(0, 60, 40)); tb = np.sort(rng.uniform(3, 57, 35))
sig = lambda t: 2 + np.sin(2 * np.pi * t / 30)
va = sig(ta) + rng.normal(0, 0.01, ta.size); vb = sig(tb) + 0.02 + rng.normal(0, 0.01, tb.size)
lo, hi = max(ta[0], tb[0]), min(ta[-1], tb[-1])
g = np.arange(np.ceil(lo), np.floor(hi) + 1)
d = np.interp(g, ta, va) - np.interp(g, tb, vb)
rms = np.sqrt(np.mean(d**2))
print(rms)
```

```python tests
import numpy as np
lo, hi = max(ta[0], tb[0]), min(ta[-1], tb[-1])
want_g = np.arange(np.ceil(lo), np.floor(hi) + 1)
assert np.array_equal(g, want_g), f"The grid should be the whole seconds from {want_g[0]:g} to {want_g[-1]:g}, inside both records."
dd = np.interp(want_g, ta, va) - np.interp(want_g, tb, vb)
assert np.allclose(d, dd) and abs(rms - np.sqrt(np.mean(dd**2))) < 1e-12, "d is A minus B on the grid, and rms its RMS."
```

::: right
Right. Outside the overlap `np.interp` would hold the end values flat and invent a difference that was never measured. The RMS difference shows B's 20 mV offset plus the noise and the interpolation error.
:::
:::

::: check
given: x0 = 10 | 20 | 50; dx = 5 | 10; y0 = 1.2 | 3.3 | 4.7; dy = 0.4 | -0.6 | 1.1; f = 0.2 | 0.4 | 0.8; let x1 = x0 + dx; let y1 = y0 + dy; let xq = x0 + f*dx
answer: y0 + dy*f
tolerance: 0.2%

## A table holds $y$ = {y0} at $x$ = {x0} and $y$ = {y1} at $x$ = {x1}. What does linear interpolation give at $x$ = {xq}?

::: right
Right. {xq} is {f} of the way from {x0} to {x1}, so $y$ moves {f} of the way from {y0} toward {y1}: {answer}.
:::

::: misses
- [y0 + dy*(1 - f)] That measures from the wrong end. The point is {f} of the way from {x0}.
- [y0 + f] That moves $y$ by the fraction itself. Scale the change in $y$, from {y0} to {y1}, by the fraction.
- [any] Not yet. Find what fraction of the interval the point is along, and move $y$ that fraction of the way.
:::
:::

::: check
kind: choice

## `np.interp(150, [0, 50, 100], [1.0, 2.0, 2.5])` asks for a value beyond the table. What does it return?

- [x] `2.5`, the last value: it clamps
- [ ] `3.0`, extending the last segment
- [ ] `nan`
- [ ] It raises an error

::: right
Right. Outside the table `np.interp` returns the end value, which is safe but silently wrong if you expected a trend. Check your queries are inside the table, or extend it, rather than trusting what comes back.
:::

::: misses
- [2] That's extrapolation. `np.interp` doesn't extrapolate; it clamps to the end value.
- [3] `np.interp` returns a number for any query; outside the table it uses the end values.
- [4] No error is raised, which is exactly why it's easy to miss.
:::
:::

::: explain
## Why does interpolating $\ln R$ against $1/T$ beat interpolating $R$ against $T$ for a thermistor table, using the same table?

::: model
Linear interpolation is exact when the data really is a straight line between the points and wrong by however much it curves. A thermistor follows $R = R_{25}e^{\beta(1/T - 1/T_{25})}$, which curves strongly in $R$ against $T$, so straight chords miss it. Taking logs gives $\ln R = \ln R_{25} + \beta(1/T - 1/T_{25})$, a straight line in $1/T$, so the same table points joined by straight lines in those coordinates trace the model exactly. Any quantity whose behavior you know can be transformed until it's nearly straight before interpolating.
:::
:::

::: practice

::: check
kind: python
given: x = 1.5 | 2.25 | 3.8

## Set `y` to `np.interp(x, [1, 2, 3, 4], [10, 20, 15, 5])` for `x` = {x}, and `y2` to the same value worked out with the straight-line formula yourself.

```python starter
import numpy as np
y = np.interp(x, [1, 2, 3, 4], [10, 20, 15, 5])
y2 = 0
print(y, y2)
```

```python solution
import numpy as np
y = np.interp(x, [1, 2, 3, 4], [10, 20, 15, 5])
xs, ys = [1, 2, 3, 4], [10, 20, 15, 5]
i = int(x) - 1
y2 = ys[i] + (ys[i + 1] - ys[i]) * (x - xs[i]) / (xs[i + 1] - xs[i])
print(y, y2)
```

```python tests
import numpy as np
assert abs(y2 - np.interp(x, [1, 2, 3, 4], [10, 20, 15, 5])) < 1e-12, "Use y0 + (y1 - y0)(x - x0)/(x1 - x0) on the interval holding x."
```
:::

::: check
kind: python
given: v = 0.5 | 1.7 | 2.9

## A sensor's calibration table maps output voltage to pressure: 0 V → 0 kPa, 1 V → 22 kPa, 2 V → 51 kPa, 3 V → 95 kPa. Set `p` to the pressure for `v` = {v} V by linear interpolation.

```python starter
p = 0
print(p)
```

```python solution
import numpy as np
p = np.interp(v, [0, 1, 2, 3], [0, 22, 51, 95])
print(p)
```

```python tests
import numpy as np
assert abs(p - np.interp(v, [0, 1, 2, 3], [0, 22, 51, 95])) < 1e-9, "Interpolate in the calibration table."
```
:::
:::
