---
title: Reading data and fitting a curve
heading: Pulling a number out of noisy measurements
eyebrow: A4 · Lesson 45 · Reading data and fitting a curve
xp: 40
---

::: hook
You measure the current through an unknown resistor at ten voltages. Every reading is off a little, because meters aren't perfect, so the points don't sit exactly on a line. What's the resistance? Picking any two points gives a different answer each time. A fit uses all of them at once and gives the best single answer the data support.
:::

::: predict
## A capacitor's voltage decays as $V_0e^{-t/\tau}$. You plot $\ln v$ against $t$. What shape do the points make?

- [ ] An exponential curve
- [x] A straight line, with slope $-1/\tau$
- [ ] A parabola
- [ ] A horizontal line

::: reveal
A straight line. $\ln(V_0e^{-t/\tau}) = \ln V_0 - t/\tau$: a constant plus a slope of $-1/\tau$ times $t$. Taking the log turns the exponential into a line, which a straight-line fit handles perfectly. That trick works for any exponential and, using logs on both axes, for any power law.
:::
:::

::: nameit
## Least-squares fits

`np.polyfit(x, y, deg)` finds the polynomial of degree `deg` that comes closest to the points, in the sense of the smallest total of squared vertical misses. For a straight line, `deg = 1`:

```
import numpy as np
slope, intercept = np.polyfit(V, I, 1)
R = 1 / slope            # Ohm's law: I = V / R
```

It returns the coefficients highest power first. `np.polyval(coeffs, x)` evaluates the fitted polynomial, handy for drawing the fit over the data.

**Making other shapes straight.** If the model isn't a polynomial, transform it into one:

| Model | Plot | Slope gives |
|---|---|---|
| $v = V_0 e^{-t/\tau}$ | $\ln v$ against $t$ | $-1/\tau$ |
| $y = kx^n$ | $\ln y$ against $\ln x$ | $n$ |

**Reading data.** Measurements usually arrive as a CSV file, one row per reading. `np.loadtxt('data.csv', delimiter=',', skiprows=1)` reads one into an array, skipping the header row; column `k` is `data[:, k]`. The labs below give the data as a text string, read the same way through `io.StringIO`.

**How good is the fit?** Look at the **residuals**, the misses `y - np.polyval(coeffs, x)`. They should look like random scatter around zero. A pattern in them, a curve or a trend, means the model is wrong, however small they are.

The labs make their own "measurements": exact values plus a little random noise from `np.random.default_rng`, seeded so the noise is the same every run.
:::

::: example
## A sensor reads 0.50, 0.75, 1.01, 1.24 and 1.50 V at 0, 25, 50, 75 and 100 °C. Fit a line.

::: solution
1. **Fit a straight line.** `np.polyfit` with degree 1 returns the least-squares slope and intercept.

```
import numpy as np
T = np.array([0, 25, 50, 75, 100])
v = np.array([0.50, 0.75, 1.01, 1.24, 1.50])
m, b = np.polyfit(T, v, 1)
print(m, b)        # 0.00996 0.502
```

2. **Read the line.** 9.96 mV per °C and 0.502 V at 0 °C: the least-squares line through the five points.
3. **Check the residuals.** The residuals, `v - (m*T + b)`, are all 10 mV or less, a sign the line fits.

**Answer:** $v = 0.502 + 0.00996\,T$ volts, with $T$ in °C: 9.96 mV per °C and 0.502 V at 0 °C.
:::
:::

::: example
## Fit a time constant to a decay without a nonlinear fitter.

::: solution
1. **Take the log.** $v = V_0e^{-t/\tau}$ becomes a straight line after a log:
   $$\ln v = \ln V_0 - t/\tau$$
2. **Fit a line to the log.** The slope is $-1/\tau$ and the intercept is $\ln V_0$.

```
m, b = np.polyfit(t, np.log(v), 1)
tau, V0 = -1 / m, np.exp(b)
```

3. **Know when it works.** Turning a curve into a line with a transformation is the oldest trick in data analysis; it works whenever the noise is small compared with the smallest readings.

**Answer:** fit a line to $\ln v$ against $t$; then $\tau = -1/m$ and $V_0 = e^b$.
:::
:::

::: check
kind: python
given: R = 1k..47k E12 Ω

## The arrays `V` and `I` hold ten noisy measurements of a resistor. Fit a straight line of `I` against `V` and set `R_fit` to the resistance it gives.

```python starter
import numpy as np

rng = np.random.default_rng(7)
V = np.linspace(1, 10, 10)
I = V / R + rng.normal(0, 0.01 / R, 10)

R_fit = 0   # replace this
print(R_fit)
```

```python solution
import numpy as np

rng = np.random.default_rng(7)
V = np.linspace(1, 10, 10)
I = V / R + rng.normal(0, 0.01 / R, 10)

slope, intercept = np.polyfit(V, I, 1)
R_fit = 1 / slope
print(R_fit)
```

```python tests
import numpy as np
slope = np.polyfit(V, I, 1)[0]
assert abs(R_fit - slope) > 1e-12, "The slope of I against V is 1/R. Turn it into a resistance."
assert abs(R_fit - 1 / slope) < 1e-9 * R, "R_fit should be 1 / slope of the fitted line of I against V."
assert abs(R_fit - R) < 0.02 * R, "The fit should land within about 2% of the true resistance."
```

::: right
Right. The fit uses every point, so the meter's errors partly cancel.
:::
:::

::: check
kind: python
given: tau = 1..9 int; V0 = 2..9 int

## The arrays `t` (in ms) and `v` (in volts) hold a noisy capacitor discharge. Fit a line to $\ln v$ against $t$ and set `tau_fit` to the time constant in ms.

```python starter
import numpy as np

rng = np.random.default_rng(3)
t = np.linspace(0, 3 * tau, 30)
v = V0 * np.exp(-t / tau) * (1 + rng.normal(0, 0.01, 30))

tau_fit = 0   # replace this
print(tau_fit)
```

```python solution
import numpy as np

rng = np.random.default_rng(3)
t = np.linspace(0, 3 * tau, 30)
v = V0 * np.exp(-t / tau) * (1 + rng.normal(0, 0.01, 30))

slope, intercept = np.polyfit(t, np.log(v), 1)
tau_fit = -1 / slope
print(tau_fit)
```

```python tests
import numpy as np
slope = np.polyfit(t, np.log(v), 1)[0]
assert abs(tau_fit - 1 / slope) > 1e-9 * tau, "The slope is −1/τ, so τ = −1/slope (watch the sign)."
assert abs(tau_fit - (-1 / slope)) < 1e-9 * tau, "tau_fit should be −1 / (slope of ln v against t)."
assert abs(tau_fit - tau) < 0.05 * tau, "The fit should give the time constant to within about 5%."
```

::: right
Right. One log turned a curve into a line.
:::
:::

::: check
kind: python

## The string `csv` holds a small log: a header row, then time in seconds and temperature in °C. Read it with `np.loadtxt` and set `mean_T` to the average temperature and `max_T` to the highest.

```python starter
import io
import numpy as np

csv = """t,T
0,21.5
60,22.1
120,23.4
180,24.0
240,23.8
300,23.1"""

data = None   # replace: read csv into an array
mean_T = 0
max_T = 0
print(mean_T, max_T)
```

```python solution
import io
import numpy as np

csv = """t,T
0,21.5
60,22.1
120,23.4
180,24.0
240,23.8
300,23.1"""

data = np.loadtxt(io.StringIO(csv), delimiter=',', skiprows=1)
mean_T = data[:, 1].mean()
max_T = data[:, 1].max()
print(mean_T, max_T)
```

```python tests
import numpy as np
assert abs(mean_T - np.mean([21.5, 22.1, 23.4, 24.0, 23.8, 23.1])) < 1e-9, "mean_T should be the average of the temperature column, data[:, 1]. Skip the header row with skiprows=1."
assert abs(max_T - 24.0) < 1e-9, "max_T should be the largest temperature, 24.0."
```

::: right
Right. Column 1 is the temperature; column 0 is time.
:::
:::

::: check
kind: choice

## A fit of $\ln y$ against $\ln x$ gives a straight line with slope 2. What does that tell you?

- [ ] $y$ grows exponentially
- [x] $y$ is proportional to $x^2$
- [ ] $y = 2x$
- [ ] $y$ doubles every step

::: right
Right. $\ln y = 2\ln x + c$ means $y = e^c x^2$: a power law with exponent 2, like a resistor's power against its voltage.
:::

::: misses
- [1] An exponential gives a straight line when you plot $\ln y$ against $x$ itself.
- [3] $y = 2x$ has slope 1 on log-log axes: the 2 is a constant factor, which only shifts the line.
- [4] That's exponential growth, a straight line of $\ln y$ against $x$.
:::
:::

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

## A platinum RTD follows $R = R_0(1 + AT + BT^2)$ above 0 °C, with $R_0$ = 100 Ω. The starter has 15 noisy readings `R` at temperatures `T` (°C). Fit a quadratic with `np.polyfit` and set `A_fit` and `B_fit` from its coefficients.

```python starter
import numpy as np
rng = np.random.default_rng(k)
T = np.linspace(0, 400, 15)
R = 100 * (1 + 3.9083e-3 * T - 5.775e-7 * T**2) + rng.normal(0, 0.005, 15)
p = np.polyfit(T, R, 1)
A_fit = p[0]
B_fit = 0
print(A_fit, B_fit)
```

```python solution
import numpy as np
rng = np.random.default_rng(k)
T = np.linspace(0, 400, 15)
R = 100 * (1 + 3.9083e-3 * T - 5.775e-7 * T**2) + rng.normal(0, 0.005, 15)
c2, c1, c0 = np.polyfit(T, R, 2)
A_fit = c1 / 100
B_fit = c2 / 100
print(A_fit, B_fit)
```

```python tests
import numpy as np
rng = np.random.default_rng(k)
TT = np.linspace(0, 400, 15)
RR = 100 * (1 + 3.9083e-3 * TT - 5.775e-7 * TT**2) + rng.normal(0, 0.005, 15)
c = np.polyfit(TT, RR, 2)
assert abs(A_fit - c[1] / 100) < 1e-12, "polyfit returns the highest power first; A is the T coefficient divided by R0 = 100."
assert abs(B_fit - c[0] / 100) < 1e-15, "B is the T² coefficient divided by R0."
assert abs(A_fit - 3.9083e-3) < 2e-5 and abs(B_fit + 5.775e-7) < 5e-8, "Your fit should land near A = 3.9083e-3 and B = -5.775e-7."
```

::: right
Right. `polyfit` returns coefficients highest power first, and dividing by $R_0$ turns them into the standard's $A$ and $B$. The small negative $B$ bends the curve by about 9 Ω at 400 °C, too much to ignore.
:::
:::

::: check
kind: choice

## After fitting a straight line, you plot the residuals (data minus fit) against $x$. They form a smooth U shape. What does that tell you?

- [x] The data curves, so a straight line is the wrong model
- [ ] The noise is too large
- [ ] The fit is as good as it can be
- [ ] There are too few points

::: right
Right. Noise scatters residuals randomly around zero. A smooth pattern is the part of the data your model can't describe, here a curvature, so try a quadratic.
:::

::: misses
- [2] Noise makes residuals scatter randomly. A smooth shape is signal the model is missing.
- [3] A good fit leaves residuals with no pattern. A U shape is curvature the line can't follow.
- [4] More points would trace the same U more clearly. The model is the problem.
:::
:::

::: explain
## Why is a fit through all your measurements better than drawing a line through two of them?

::: model
Every measurement has some random error. A line through two points carries both of their errors in full, and a different pair gives a different line. A least-squares fit balances all the points at once, so random errors tend to cancel and the result is less sensitive to any single bad reading. It also leaves residuals you can inspect, which tell you whether the straight-line model fits at all.
:::
:::

::: practice

::: check
kind: python
given: R = 2..50 sig 2

## `I` (amps) and `P` (watts) hold noisy measurements of a resistor's power. Fit $P$ against $I$ with a degree-2 polynomial and set `R_fit` to its $I^2$ coefficient.

```python starter
import numpy as np

rng = np.random.default_rng(11)
I = np.linspace(0.1, 2, 15)
P = R * I**2 * (1 + rng.normal(0, 0.01, 15))
R_fit = 0
print(R_fit)
```

```python solution
import numpy as np

rng = np.random.default_rng(11)
I = np.linspace(0.1, 2, 15)
P = R * I**2 * (1 + rng.normal(0, 0.01, 15))
R_fit = np.polyfit(I, P, 2)[0]
print(R_fit)
```

```python tests
import numpy as np
assert abs(R_fit - np.polyfit(I, P, 2)[0]) < 1e-9 * R, "R_fit should be the first coefficient of np.polyfit(I, P, 2), the one multiplying I²."
```
:::

::: check
kind: python
given: n = 2 | 3; k = 2..9 int

## `x` and `y` follow $y = kx^n$ with a little noise. Fit $\ln y$ against $\ln x$ and set `n_fit` to the exponent.

```python starter
import numpy as np

rng = np.random.default_rng(5)
x = np.linspace(1, 10, 20)
y = k * x**n * (1 + rng.normal(0, 0.01, 20))
n_fit = 0
print(n_fit)
```

```python solution
import numpy as np

rng = np.random.default_rng(5)
x = np.linspace(1, 10, 20)
y = k * x**n * (1 + rng.normal(0, 0.01, 20))
n_fit = np.polyfit(np.log(x), np.log(y), 1)[0]
print(n_fit)
```

```python tests
import numpy as np
assert abs(n_fit - np.polyfit(np.log(x), np.log(y), 1)[0]) < 1e-9, "n_fit should be the slope of ln y against ln x."
assert abs(n_fit - n) < 0.05, "The fitted exponent should come out close to the true one."
```
:::
:::
