---
title: "Lab: first-order models from data"
heading: Measuring, simulating and checking first-order systems
eyebrow: A8 · Lesson 7 · Lab: first-order models from data
xp: 60
---

::: hook
A first-order model is only useful once you know its time constant, and in practice that comes from measurements: a scope trace, a logged temperature, a recorded speed. In this lab you'll extract $\tau$ from noisy samples two ways, simulate a heat sink through a power pulse and check the result against the exact solution, and time a falling object with quadratic drag, a nonlinear first-order equation, against its formula.
:::

::: play
- The curve is a discharge $v = 5e^{-t/\tau}$ V on a logarithmic voltage axis.
- On this axis an exponential is a straight line, and its slope gives $\tau$: the voltage falls by a factor $e$ every $\tau$.
- Change $\tau$ and watch the line's steepness change. Fitting a line to $\ln v$ is the most reliable way to read $\tau$ from data.
:::

```sim plot
view: graph
x: t = 0..10 ms
y: v = 0.001..10 V log
slider: tau = 0.5..5 step 0.1 = 2 ms
plot: 5*exp(-t/tau) | label: v(t)
readout: slope of ln v, per ms = -1/tau | digits: 4
readout: time to fall by 10 times, ms = tau*ln(10) | digits: 4
```

::: predict
## You fit a straight line to $\ln v$ against $t$ for a discharge and get a slope of $-0.5$ per ms. What is $\tau$?

- [ ] 0.5 ms
- [x] 2 ms
- [ ] 0.69 ms
- [ ] 5 ms

::: reveal
2 ms. $\ln v = \ln V_0 - t/\tau$, so the slope is $-1/\tau$ and $\tau = 1/0.5 = 2$ ms. The intercept gives $V_0$. Using every sample, rather than one point at 37%, averages out noise.
:::
:::

::: nameit
## Fitting $\tau$

Two dependable methods for a first-order response:
- **Log-linear fit:** for a decay toward zero, fit a line to $\ln v$ against $t$ with `np.polyfit(t, np.log(v), 1)`; $\tau = -1/\text{slope}$. Leave out samples near zero, where noise dominates the logarithm.
- **Rise time:** for a step response, find where it crosses 10% and 90% of the final value, interpolating between samples, and divide the difference by $\ln 9 = 2.197$.

## Simulating and checking

Euler's method, $y_{n+1} = y_n + hf(t_n, y_n)$, is enough for a first-order system if $h$ is a small fraction of $\tau$; its error shrinks in proportion to $h$. Always check a simulation against an exact solution where one exists, then trust it where none does.

## Quadratic drag

An object falling through air obeys $m\dot v = mg - bv^2$, which is separable (and Bernoulli). It approaches the terminal velocity $v_t = \sqrt{mg/b}$ along

$$v = v_t\tanh\frac{gt}{v_t}$$

reaching 90% of $v_t$ at $t = \frac{v_t}{g}\tanh^{-1}0.9 = 1.472\frac{v_t}{g}$.
:::

::: example
## A transistor on a heat sink ($R_\theta$ = 5 K/W, $C_\theta$ = 20 J/K, 25 °C air) dissipates 10 W for 60 s, then nothing. What is its temperature at 120 s?

::: solution
1. **Time constant and target.**
   $$\begin{aligned} \tau &= R_\theta C_\theta \\ &= 100\ \text{s} \end{aligned}$$
   While the power is on, the temperature heads for $25 + 10 \times 5 = 75$ °C.
2. **Temperature at 60 s.**
   $$\begin{aligned} T(60) &= 25 + 50(1 - e^{-0.6}) \\ &= 47.6\ \text{°C} \end{aligned}$$
3. **Cooling until 120 s.** Then it cools toward 25 °C from there:
   $$\begin{aligned} T(120) &= 25 + 22.6e^{-0.6} \\ &= 37.4\ \text{°C} \end{aligned}$$
4. **Pulse ratings.** A 60 s pulse is too short for it to come anywhere near 75 °C, which is why pulse ratings of power devices are higher than their continuous ratings.

**Answer:** the transistor is at 37.4 °C at 120 s, after peaking at 47.6 °C at 60 s.
:::
:::

::: example
## A 0.1 kg object falls with drag coefficient $b$ = 0.01 kg/m. What is its terminal velocity, and when does it reach 90% of it?

::: solution
1. **Terminal velocity.**
   $$\begin{aligned} v_t &= \sqrt{0.1 \times 9.81/0.01} \\ &= 9.90\ \text{m/s} \end{aligned}$$
2. **Time to 90%.**
   $$\begin{aligned} t &= \frac{9.90}{9.81}\tanh^{-1}0.9 \\ &= 1.009 \times 1.472 \\ &= 1.49\ \text{s} \end{aligned}$$
3. **Compare with no drag.** Without drag it would reach 8.91 m/s in 0.91 s; drag stretches the time by about 60%.

**Answer:** the terminal velocity is 9.90 m/s, and it reaches 90% of that at 1.49 s.
:::
:::

::: check
given: s = 0.25 | 0.5 | 2
answer: 1/s
unit: ms
tolerance: 0.5%

## A log-linear fit to a discharge gives a slope of $-$ {s} per ms. What is $\tau$?

::: right
Right. $\tau = 1/|\text{slope}|$ = {answer}.
:::

::: misses
- [s] Invert the slope.
- [any] Not yet. $\ln v = \ln V_0 - t/\tau$.
:::
:::

::: check
given: m = 0.05 | 0.2; b = 0.01 | 0.02
answer: sqrt(m*9.81/b)
unit: m/s
tolerance: 0.5%

## An object of {m} kg falls with drag coefficient {b} kg/m. What is its terminal velocity?

::: right
Right. $\sqrt{mg/b}$ = {answer}.
:::

::: misses
- [m*9.81/b] Take the square root: drag goes as $v^2$.
- [any] Not yet. At terminal velocity, $bv^2 = mg$.
:::
:::

::: check
kind: python

## Fit $\tau$ from the noisy discharge samples in the starter by a log-linear fit, and set `tau` (in ms) and `V0`.

```python starter
import numpy as np

t = np.linspace(0, 10, 51)
v = 5 * np.exp(-t / 2) * (1 + 0.01 * np.sin(13 * t))
tau = V0 = 1.0
print(tau, V0)
```

```python solution
import numpy as np

t = np.linspace(0, 10, 51)
v = 5 * np.exp(-t / 2) * (1 + 0.01 * np.sin(13 * t))
slope, intercept = np.polyfit(t, np.log(v), 1)
tau = -1 / slope
V0 = np.exp(intercept)
print(tau, V0)
```

```python tests
assert abs(tau - 2) < 0.02, f"The data were made with tau = 2 ms; the fit should be within 1%; got {tau}."
assert abs(V0 - 5) < 0.05, f"The fit should give V0 near 5 V; got {V0}."
```

::: right
Right. Using all 51 samples, the 1% ripple barely moves the fitted time constant.
:::
:::

::: check
kind: python

## Simulate the heat-sink example with Euler's method, $h$ = 0.01 s: $C\dot T = P(t) - (T - 25)/R$ with 10 W for $t < 60$ s and 0 after. Set `T120` to the temperature at 120 s and `exact` to the formula's value.

```python starter
import math

T120 = exact = 25.0
print(T120, exact)
```

```python solution
import math

R, C, h = 5.0, 20.0, 0.01
T = 25.0
for n in range(12000):
    t = n * h
    P = 10.0 if t < 60 else 0.0
    T += h * (P - (T - 25) / R) / C
T120 = T
exact = 25 + 50 * (1 - math.exp(-0.6)) * math.exp(-0.6)
print(T120, exact)
```

```python tests
import math
assert abs(exact - (25 + 50 * (1 - math.exp(-0.6)) * math.exp(-0.6))) < 1e-9, "exact should be 25 + 50(1 - e^-0.6)e^-0.6."
assert abs(T120 - exact) < 0.01, f"Euler with h = 0.01 s should land within 0.01 C of {exact:.3f}; got {T120:.4f}."
```

::: right
Right. With $h$ ten thousand times smaller than $\tau$, Euler's error is a few thousandths of a degree.
:::
:::

::: check
kind: python

## Step $m\dot v = mg - bv^2$ from rest with $m$ = 0.1 kg, $b$ = 0.01 kg/m and $h$ = 0.0001 s until $v$ reaches 90% of $v_t$. Set `t90` to that time, interpolated within the last step, and `formula` to $\frac{v_t}{g}\tanh^{-1}0.9$.

```python starter
import math

t90 = formula = 0.0
print(t90, formula)
```

```python solution
import math

m, b, g, h = 0.1, 0.01, 9.81, 1e-4
vt = math.sqrt(m * g / b)
v, t = 0.0, 0.0
while v < 0.9 * vt:
    v_old = v
    v += h * (g - b * v * v / m)
    t += h
t90 = t - h + (0.9 * vt - v_old) / (v - v_old) * h
formula = vt / g * math.atanh(0.9)
print(t90, formula)
```

```python tests
import math
vt = math.sqrt(0.1 * 9.81 / 0.01)
assert abs(formula - vt / 9.81 * math.atanh(0.9)) < 1e-9, "formula should be (vt/g) atanh(0.9)."
assert abs(t90 - formula) < 0.002, f"The stepped time should match {formula:.4f} s; got {t90:.5f}."
```

::: right
Right. The nonlinear equation and its tanh solution agree, and the same loop would work with any drag law, where no formula exists.
:::
:::

::: check
kind: python
given: tau = 0.8 | 1.5 | 3

## Sample the step response $1 - e^{-t/\tau}$ ($\tau$ = {tau} ms) every 0.01 ms out to $8\tau$. Find the 10% and 90% crossings by linear interpolation and set `tau_est` to their difference divided by $\ln 9$.

```python starter
import numpy as np

tau_est = 1.0
print(tau_est)
```

```python solution
import numpy as np

t = np.arange(0, 8 * tau, 0.01)
y = 1 - np.exp(-t / tau)

def crossing(level):
    k = np.argmax(y >= level)
    return t[k - 1] + (level - y[k - 1]) / (y[k] - y[k - 1]) * (t[k] - t[k - 1])

tau_est = (crossing(0.9) - crossing(0.1)) / np.log(9)
print(tau_est)
```

```python tests
assert abs(tau_est - tau) < 0.005 * tau, f"The rise-time method should recover tau = {tau} ms within 0.5%; got {tau_est}."
```

::: right
Right. Interpolating between samples keeps the error far below the sample spacing.
:::
:::

::: check
kind: python

## A drink's temperature is logged every 2 minutes in a 20 °C room (data in the starter). Fit Newton's law of cooling by a log-linear fit of $T - 20$, set `k` (per minute), and set `t40` to the predicted time to reach 40 °C from the start at 90 °C.

```python starter
import numpy as np

t = np.arange(0, 31, 2.0)
T = 20 + 70 * np.exp(-0.05596 * t) + 0.2 * np.sin(5 * t)
k = t40 = 0.0
print(k, t40)
```

```python solution
import numpy as np

t = np.arange(0, 31, 2.0)
T = 20 + 70 * np.exp(-0.05596 * t) + 0.2 * np.sin(5 * t)
slope, _ = np.polyfit(t, np.log(T - 20), 1)
k = -slope
t40 = np.log(70 / 20) / k
print(k, t40)
```

```python tests
assert abs(k - 0.05596) < 0.001, f"The cooling constant should come out near 0.056 per minute; got {k}."
assert abs(t40 - 22.39) < 0.3, f"It reaches 40 C after about 22.4 minutes; got {t40}."
```

::: right
Right. The fitted constant predicts the crossing to within a few seconds, despite the ripple on every reading.
:::
:::

::: explain
## Why is a log-linear fit over many samples better than reading the time at which a decay reaches 37%?

::: model
Reading one point uses one sample's worth of information: any noise on that sample, or on the starting value that defines 37%, goes straight into $\tau$. A straight-line fit to $\ln v$ uses every sample, and random errors partly cancel in the average, so the estimate's uncertainty shrinks roughly as one over the square root of the number of points. Taking the logarithm turns the exponential into a line, which makes the fit linear least squares with a closed-form answer. The one caution is the tail: as $v$ approaches the noise floor, $\ln v$ becomes erratic, so those samples should be left out.
:::
:::

::: practice

::: check
given: s = 0.01..10
answer: 1/s
unit: ms
tolerance: 0.5%

## $\tau$ from a log-linear slope of $-$ {s} per ms, in ms?

::: misses
- [any] $1/|\text{slope}|$.
:::
:::

::: check
given: m = 0.01..1; b = 0.001..0.1
answer: sqrt(m*9.81/b)
unit: m/s
tolerance: 0.5%

## Terminal velocity for {m} kg with $b$ = {b} kg/m, in m/s?

::: misses
- [any] $\sqrt{mg/b}$.
:::
:::
:::
