---
title: Systems lab
heading: Discretizing models and measuring noise bandwidth in Python
eyebrow: C9 · Lesson 50 · Systems lab
xp: 50
---

::: hook
Lessons 45 to 48 dealt with systems described in continuous time that have to live in discrete time, and with what systems do to noise. This lab turns those into code: a zero-order-hold equivalent, a measurement of how far forward Euler drifts, a matrix exponential, the discrete state-space model of any linear system, and a numerical noise bandwidth for any digital filter.
:::

::: play
- The four curves are where four methods put the discrete pole of $\dot y = -ay$, against aT. The ZOH pole, $e^{-aT}$, is exact.
- Forward Euler's pole, $1 - aT$, falls below 0 at aT = 1 (ringing) and below −1 at aT = 2 (unstable). Backward Euler's, $1/(1 + aT)$, is always stable but too slow. Tustin's, $(1 - aT/2)/(1 + aT/2)$, stays close for longer and never leaves the unit circle.
- The readouts compare them at the slider's aT.
:::

```sim plot
view: graph
x: x = 0..3
y: p = -2..1.1
slider: v = 0..3 step 0.05 = 0.5
plot: exp(-x) | label: zero-order hold (exact)
plot: 1 - x | label: forward Euler
plot: 1/(1 + x) | label: backward Euler
plot: (1 - x/2)/(1 + x/2) | label: Tustin
readout: exact = exp(-v) | digits: 4
readout: forward Euler = 1 - v | digits: 4
readout: backward Euler = 1/(1 + v) | digits: 4
readout: Tustin = (1 - v/2)/(1 + v/2) | digits: 4
```

::: predict
## At aT = 0.1, how far is forward Euler's pole from the exact one?

- [ ] 0.1
- [ ] 0.01
- [x] About 0.005
- [ ] 0

::: reveal
About 0.005: $e^{-0.1} = 0.9048$ against 0.9. The error is about $(aT)^2/2$ per step, which is why Euler is a first-order method: halve the step and each step's error falls by four, but there are twice as many steps, so the total error halves.
:::
:::

::: nameit
## What the code does

- **ZOH equivalent of a first-order lag** $a/(s + a)$: pole $p = e^{-aT}$, input gain $1 - p$.
- **Euler's drift**: step $y[k+1] = y[k] + aT(u - y[k])$ and compare with $1 - e^{-akT}$.
- **Matrix exponential**: $e^{A} = \sum A^k/k!$ converges for every A but slowly when A is large, so scale it down by $2^s$ until it's small, sum about a dozen terms, then square the result s times: $e^{A} = (e^{A/2^s})^{2^s}$.
- **Discrete state space**: the exponential of the block matrix $\begin{bmatrix} A & B \\ 0 & 0\end{bmatrix}T$ is $\begin{bmatrix} A_d & B_d \\ 0 & I\end{bmatrix}$, which gives both $A_d = e^{AT}$ and $B_d$ in one step, even when A can't be inverted.
- **Noise bandwidth of a digital filter**: integrate $\lvert H(e^{j\omega})\rvert^2$ from 0 to π, scale by $f_s/2\pi$, and divide by the DC power gain $\lvert H(1)\rvert^2$.
:::

::: example
## A 4-point moving average runs at 1 kHz. What is its noise bandwidth?

::: solution
1. **Parseval.**
   $$\begin{aligned} \frac{1}{2\pi}\int_{-\pi}^{\pi}\lvert H\rvert^2d\omega &= \sum h^2 \\ &= 4 \times (1/4)^2 \\ &= 1/4 \end{aligned}$$
2. **One side.** So the one-sided integral is
   $$\frac{1}{2\pi}\int_0^\pi\lvert H\rvert^2d\omega = 1/8$$
3. **Scale to hertz.** Multiply by $f_s$ and divide by $\lvert H(1)\rvert^2 = 1$:
   $$1000 \times 1/8 = 125\ \text{Hz}$$
4. **In general.** An N-point average has a noise bandwidth of $f_s/2N$.

**Answer:** the noise bandwidth is 125 Hz.
:::
:::

::: example
## Discretize the double integrator $\dot x_1 = x_2$, $\dot x_2 = u$ with a zero-order hold at step T.

::: solution
1. **A is nilpotent.** Since $A^2 = 0$, this is exact:
   $$\begin{aligned} e^{AT} &= I + AT \\ &= \begin{bmatrix} 1 & T \\ 0 & 1\end{bmatrix} \end{aligned}$$
2. **Input matrix.**
   $$\begin{aligned} B_d &= \int_0^T e^{A\tau}B\,d\tau \\ &= \begin{bmatrix} T^2/2 \\ T\end{bmatrix} \end{aligned}$$
3. **What it means.** Position gains $\tfrac12 uT^2$ and velocity $uT$ per step, the familiar constant-acceleration formulas.
4. **Method.** A can't be inverted here, which is why the block-matrix method is the safe one.

**Answer:** $e^{AT}$ has rows [1, T] and [0, 1], and $B_d = [T^2/2,\ T]^T$.
:::
:::

::: check
given: a = 1 | 10 | 100; T = 0.001 | 0.01 | 0.02
answer: exp(-a*T) - (1 - a*T)
tolerance: 0.5%

## How much larger is the exact pole $e^{-aT}$ than forward Euler's, with a = {a} and T = {T}?

::: right
Right: {answer}.
:::

::: misses
- [any] Not yet. $e^{-aT} - (1 - aT)$.
:::
:::

::: check
kind: python

## Write `euler_error(a, T, n)`: step forward Euler on $\dot y = a(1 - y)$ from y = 0 for n steps of T, and return the largest absolute difference from the exact $1 - e^{-akT}$ at steps k = 1 to n.

```python starter
def euler_error(a, T, n):
    return 0.0
```

```python solution
import math

def euler_error(a, T, n):
    y, worst = 0.0, 0.0
    for k in range(1, n + 1):
        y += a * T * (1 - y)
        worst = max(worst, abs(y - (1 - math.exp(-a * k * T))))
    return worst
```

```python tests
assert abs(euler_error(1, 0.1, 50) - 0.019201) < 1e-6, f"a = 1, T = 0.1: 0.0192, got {euler_error(1, 0.1, 50)}."
assert abs(euler_error(1, 0.01, 500) - 0.0018471) < 1e-6, f"Ten times smaller steps, ten times smaller error: 0.00185, got {euler_error(1, 0.01, 500)}."
assert abs(euler_error(10, 0.05, 50) - 0.117879) < 1e-6, f"aT = 0.5 is already 12% off: got {euler_error(10, 0.05, 50)}."
```

::: right
Right. The error shrinks in proportion to the step: a first-order method.
:::
:::

::: check
kind: python

## Write `expm(A)`: the matrix exponential of a square numpy array, by scaling and squaring with a Taylor series.

```python starter
import numpy as np

def expm(A):
    return np.eye(len(A)) + np.asarray(A, dtype=float)
```

```python solution
import numpy as np

def expm(A):
    A = np.asarray(A, dtype=float)
    norm = np.max(np.sum(np.abs(A), axis=1)) if A.size else 0.0
    s = max(0, int(np.ceil(np.log2(norm))) + 1) if norm > 0.5 else 0
    X = A / 2 ** s
    E, term = np.eye(len(A)), np.eye(len(A))
    for k in range(1, 20):
        term = term @ X / k
        E = E + term
    for _ in range(s):
        E = E @ E
    return E
```

```python tests
import numpy as np
assert np.allclose(expm([[-1.0, 0.0], [0.0, -2.0]]), np.diag([np.exp(-1), np.exp(-2)]), atol=1e-12), "A diagonal A exponentiates each entry."
t = 3.0
assert np.allclose(expm([[0.0, t], [-t, 0.0]]), [[np.cos(t), np.sin(t)], [-np.sin(t), np.cos(t)]], atol=1e-10), "A rotation generator gives a rotation."
assert np.allclose(expm([[0.0, 2.0], [0.0, 0.0]]), [[1.0, 2.0], [0.0, 1.0]], atol=1e-12), "A nilpotent A stops after the linear term."
assert np.allclose(expm([[-50.0, 0.0], [0.0, -0.5]]), np.diag([np.exp(-50), np.exp(-0.5)]), atol=1e-12), "Large entries need the scaling step."
```

::: right
Right. Scaling keeps the series short and accurate; squaring puts the size back.
:::
:::

::: check
kind: python

## Write `c2d(A, B, T)`: the zero-order-hold discretization, returning `(Ad, Bd)`, using the exponential of the block matrix $\begin{bmatrix} A & B \\ 0 & 0\end{bmatrix}T$. Use your own matrix exponential (one is provided).

```python starter
import numpy as np

def expm(A):
    A = np.asarray(A, dtype=float)
    norm = np.max(np.sum(np.abs(A), axis=1))
    s = max(0, int(np.ceil(np.log2(norm))) + 1) if norm > 0.5 else 0
    X, E, term = A / 2 ** s, np.eye(len(A)), np.eye(len(A))
    for k in range(1, 20):
        term = term @ X / k
        E = E + term
    for _ in range(s):
        E = E @ E
    return E

def c2d(A, B, T):
    A = np.asarray(A, dtype=float)
    return np.eye(len(A)) + A * T, np.asarray(B, dtype=float) * T
```

```python solution
import numpy as np

def expm(A):
    A = np.asarray(A, dtype=float)
    norm = np.max(np.sum(np.abs(A), axis=1))
    s = max(0, int(np.ceil(np.log2(norm))) + 1) if norm > 0.5 else 0
    X, E, term = A / 2 ** s, np.eye(len(A)), np.eye(len(A))
    for k in range(1, 20):
        term = term @ X / k
        E = E + term
    for _ in range(s):
        E = E @ E
    return E

def c2d(A, B, T):
    A, B = np.asarray(A, dtype=float), np.asarray(B, dtype=float)
    n, m = A.shape[0], B.shape[1]
    M = np.zeros((n + m, n + m))
    M[:n, :n], M[:n, n:] = A, B
    E = expm(M * T)
    return E[:n, :n], E[:n, n:]
```

```python tests
import numpy as np
Ad, Bd = c2d([[-2.0]], [[2.0]], 0.1)
assert np.allclose(Ad, [[np.exp(-0.2)]]) and np.allclose(Bd, [[1 - np.exp(-0.2)]]), f"A first-order lag: Ad = e^(-aT), Bd = 1 - e^(-aT); got {Ad}, {Bd}."
Ad, Bd = c2d([[0.0, 1.0], [0.0, 0.0]], [[0.0], [1.0]], 0.5)
assert np.allclose(Ad, [[1, 0.5], [0, 1]]) and np.allclose(Bd, [[0.125], [0.5]]), f"The double integrator: [[1, T], [0, 1]] and [T²/2, T]; got {Ad}, {Bd}."
Ad, Bd = c2d([[0.0, 1.0], [-2.0, -3.0]], [[0.0], [1.0]], 0.1)
x = np.zeros((2, 1))
for _ in range(100):
    x = Ad @ x + Bd
assert abs(x[0, 0] - (0.5 - np.exp(-10) + 0.5 * np.exp(-20))) < 1e-9, "The discrete step response should match the exact one at t = 10."
```

::: right
Right. One exponential gives both matrices, with no inverse to fail.
:::
:::

::: check
kind: python

## Write `noise_bandwidth(b, a, fs)`: the one-sided noise bandwidth in hertz of the digital filter with numerator b and denominator a (coefficients of $z^{-1}$), by integrating $\lvert H\rvert^2$ numerically from 0 to π.

```python starter
def noise_bandwidth(b, a, fs):
    return fs / 2
```

```python solution
import numpy as np

def noise_bandwidth(b, a, fs):
    w = np.linspace(0, np.pi, 20001)
    z = np.exp(-1j * w)
    H = np.polyval(np.asarray(b, dtype=float)[::-1], z) / np.polyval(np.asarray(a, dtype=float)[::-1], z)
    P = np.abs(H) ** 2
    integral = np.sum((P[1:] + P[:-1]) / 2) * (w[1] - w[0])
    return fs / (2 * np.pi) * integral / P[0]
```

```python tests
import math
assert abs(noise_bandwidth([0.25] * 4, [1], 1000) - 125) < 0.01, f"A 4-point average at 1 kHz: 125 Hz, got {noise_bandwidth([0.25] * 4, [1], 1000)}."
assert abs(noise_bandwidth([0.2], [1, -0.8], 1000) - 55.556) < 0.01, f"A smoother with α = 0.2: 55.56 Hz, got {noise_bandwidth([0.2], [1, -0.8], 1000)}."
W = math.tan(math.pi * 10 / 1000); k = W / (1 + W)
assert abs(noise_bandwidth([k, k], [1, (W - 1) / (W + 1)], 1000) - 15.234) < 0.01, "A bilinear low-pass at 10 Hz: 15.23 Hz, slightly below the analog π/2 · 10."
```

::: right
Right. The same number tells you how much white noise any filter lets through.
:::
:::

::: explain
## Why is the block-matrix exponential a better way to get $B_d$ than the formula $A^{-1}(e^{AT} - I)B$?

::: model
The formula needs A to be invertible, and many important systems have a pole at zero, an integrator, which makes A singular: the double integrator, a motor's position, any system with a free coordinate. Even when A is invertible but nearly singular, inverting it amplifies rounding errors. The block matrix packs A and B together so that its exponential contains $e^{AT}$ in one corner and exactly $\int_0^T e^{A\tau}d\tau\,B$ in another, which is $B_d$ by definition, without ever inverting anything. It's one well-behaved computation that works for every linear system.
:::
:::
