---
title: Discrete-time design and implementation
heading: Specifications in the z-plane, choosing the sample rate from the phase it costs, the velocity form of PI, coefficient precision near z = 1, and the delays a computer adds
eyebrow: S9 · Lesson 42 · Discrete-time design and implementation
xp: 50
---

::: hook
Lesson 41 turned continuous plants into discrete ones and continuous controllers into difference equations. Running a controller on a microcontroller raises the questions that come next. How fast must it sample? Where in the z-plane should the poles go to meet a time-domain specification? How should the PI law be written so that saturation and mode switches don't upset it? And how many bits does a coefficient need when the pole it sets sits a hair inside the unit circle?
:::

::: play
- The curve is the phase lost at a loop's crossover $\omega_c$ to a zero-order hold plus one sample of computation delay, $1.5\,\omega_cT$, against the ratio of sample rate to crossover frequency, $f_s/f_c$.
- Sampling 20 times faster than crossover costs 27°; 100 times, 5.4°.
- That's why the usual advice samples 10 to 40 times the closed-loop bandwidth, and why fast loops push for computation in under one sample.
:::

```sim plot
view: graph
x: r = 5..200 log
y: P = 0..120
plot: 1.5*2*pi/r*180/pi | label: phase lost, degrees, against fs/fc
```

::: predict
## A loop crosses over at 50 rad/s. Its controller computes for one full sample before updating the output. What sample rate keeps the lost phase under 10°?

- [ ] About 50 Hz
- [ ] About 100 Hz
- [x] About 430 Hz
- [ ] About 5 kHz

::: reveal
The hold costs about T/2 of delay and the computation another T: 1.5T in all, so $1.5 \times 50 \times T \le 10° = 0.175$ rad gives T ≤ 2.3 ms, a sample rate of at least 430 Hz, about 54 times the 8 Hz crossover. Updating the output right after the measurement, rather than a sample later, would cut the requirement to a third.
:::
:::

::: nameit
## Specifications in the z-plane

A continuous pole s maps to $z = e^{sT}$. So a decay rate σ becomes a circle of radius $e^{-\sigma T}$ (a 2% settling time $t_s$ needs every pole inside radius $e^{-4T/t_s}$), a damped frequency $\omega_d$ becomes an angle $\omega_dT$, and a damping ratio ζ becomes a logarithmic spiral from z = 1 toward the origin. A desired pair $-\zeta\omega_n \pm j\omega_d$ gives the discrete polynomial
$$z^2 - 2e^{-\zeta\omega_nT}\cos(\omega_dT)\,z + e^{-2\zeta\omega_nT}$$
and pole placement, Ackermann's formula and the root locus all work on the discrete model just as they do in s.

## Choosing the sample rate

The hold delays the signal by about T/2, and a controller that updates its output one sample after measuring adds T more. At crossover these cost $\omega_cT/2$ and $\omega_cT$ radians of phase margin. Sampling 10 to 40 times the closed-loop bandwidth keeps the loss acceptable; anti-aliasing filters ahead of the converter add their own lag on top.

## The velocity form of PI

Instead of computing $u_k = K_pe_k + K_iT\sum e$, compute the change:
$$u_k = u_{k-1} + K_p(e_k - e_{k-1}) + K_iTe_k$$
then clamp $u_k$ to the actuator's limits. Because $u_{k-1}$ is the clamped value actually applied, there's no hidden integral to wind up, and switching from manual to automatic is bumpless: the controller starts from whatever output was applied.

## Precision near z = 1

A slow pole sampled fast sits close to 1: $z = e^{-T/\tau} \approx 1 - T/\tau$. Storing z with a step of $2^{-B}$ changes $1 - z$ by up to half a step, a relative error in τ of about $2^{-B-1}\tau/T$, which grows as the sample rate rises. Writing the filter in terms of $1 - z$, or using more bits, fixes it.
:::

::: example
## A continuous design wants ζ = 0.7 and $\omega_n$ = 10 rad/s. With T = 20 ms, where should the discrete poles go?

::: solution
1. **Continuous poles.**
   $$s = -7 \pm j7.14$$
2. **Map them to z.**
   $$\begin{aligned} r &= e^{-7 \times 0.02} \\ &= 0.869 \\ \theta &= 7.14 \times 0.02 \\ &= 0.143\ \text{rad} \end{aligned}$$
   so $z = 0.861 \pm j0.124$.
3. **Characteristic polynomial.**
   $$z^2 - 1.721z + 0.756$$
4. **What it reproduces.** Placing the sampled plant's poles there reproduces the continuous response at the sampling instants, though the hold's lag shows up as slightly more overshoot unless T is short.

**Answer:** at $z = 0.861 \pm j0.124$, the roots of $z^2 - 1.721z + 0.756$.
:::
:::

::: example
## A filter pole for a 1 s time constant runs at 1 kHz. Its coefficient $z = e^{-0.001}$ is stored with 10 fractional bits. What time constant does the filter really have?

::: solution
1. **Exact coefficient.**
   $$\begin{aligned} z &= e^{-0.001} \\ &= 0.9990005 \end{aligned}$$
2. **Quantize to 10 bits.** The nearest multiple of 1/1024 is
   $$1023/1024 = 0.9990234$$
3. **Resulting time constant.**
   $$\begin{aligned} \tau &= \frac{-0.001\ \text{s}}{\ln 0.9990234} \\ &= 1.0235\ \text{s} \end{aligned}$$
   2.3% long.
4. **With 16 bits.** It's 0.9925 s, still 0.75% off, because the pole is only one part in a thousand from 1.
5. **The fix.** Storing $1 - z$ instead, or sampling the slow filter at a lower rate, solves it.

**Answer:** about 1.0235 s, 2.3% longer than the intended 1 s.
:::
:::

::: example
## A PI controller ($K_p$ = 0.5, $K_iT$ = 0.1 per sample) runs against a limit of ±1. The error is +1 for 50 samples, then becomes −1. What does each form do at the switch?

::: solution
1. **Position form.** Its integral climbs during the 50 samples to
   $$50 \times 0.1 = 5$$
2. **After the switch.** Its output stays clamped at +1 until the integral unwinds to 1.5: about 35 more samples of full drive in the wrong direction.
3. **Velocity form.** At the first sample after the switch it computes
   $$\begin{aligned} u &= 1 + 0.5(-1 - 1) \\ &\quad + 0.1(-1) \\ &= -0.1 \end{aligned}$$
4. **Why it reverses at once.** It never stored more than the clamped output.

**Answer:** the position form keeps driving +1 for about 35 more samples, while the velocity form reverses at once, to −0.1.
:::
:::

::: check
kind: parts
given: z = 0.5 | 0.7 | 0.9; w = 5 | 20; T = 5 | 20 | 50

## A continuous design has ζ = {z}, $\omega_n$ = {w} rad/s, and the controller samples every {T} ms.

::: part
answer: exp(-z*w*T*1e-3)
tolerance: 0.5%

### What radius should the discrete poles have?

::: misses
- [any] $e^{-\zeta\omega_nT}$.
:::
:::

::: part
answer: w*sqrt(1 - z^2)*T*1e-3
unit: rad
tolerance: 0.5%

### At what angle?

::: misses
- [w*T*1e-3] Use the damped frequency $\omega_d = \omega_n\sqrt{1 - \zeta^2}$.
- [any] $\omega_dT$.
:::
:::
:::

::: check
kind: parts
given: w = 10 | 100 | 1000; f = 0.2 | 1 | 10

## A loop crosses over at {w} rad/s and samples at {f} kHz, updating its output one sample after each measurement.

::: part
answer: 1.5*w/(f*1e3)*180/pi
unit: °
tolerance: 0.5%

### How much phase do the hold and the computation delay cost at crossover?

::: misses
- [0.5*w/(f*1e3)*180/pi] That's the hold alone; the computation adds a full sample.
- [any] $1.5\omega_cT$.
:::
:::
:::

::: check
kind: parts
given: w = 20 | 100 | 500; P = 5 | 10 | 20

## A loop crosses over at {w} rad/s and may lose at most {P}° to a hold plus one sample of computation.

::: part
answer: 1.5*w/(P*pi/180)/(2*pi)/1e3
unit: kHz
tolerance: 0.5%

### What is the lowest sample rate?

::: misses
- [any] Solve $1.5\omega_cT = $ {P}°, then $f_s = 1/T$.
:::
:::
:::

::: check
kind: parts
given: t = 0.1 | 1 | 10; f = 1 | 10; B = 12 | 16 | 24

## A first-order filter with τ = {t} s runs at {f} kHz, its pole stored with {B} fractional bits.

::: part
answer: 1 - exp(-1/(t*f*1e3))
tolerance: 0.5%

### How far from 1 is the exact pole?

::: misses
- [any] $1 - e^{-T/\tau}$.
:::
:::

::: part
answer: 2^(-B - 1)/(1 - exp(-1/(t*f*1e3)))*100
unit: %
tolerance: 1%

### What's the worst relative error in τ from rounding?

::: misses
- [2^(-B)/(1 - exp(-1/(t*f*1e3)))*100] Rounding errs by at most half a step.
- [any] Half a step over the distance from 1.
:::
:::
:::

::: check
kind: parts
given: K = 0.5 | 2; I = 0.05 | 0.2; u = 0.3 | 0.8; e = 1 | 2; d = -1 | -0.5

## A velocity-form PI ($K_p$ = {K}, $K_iT$ = {I} per sample) applied {u} last sample with error {e}; now the error is {d}.

::: part
answer: u + K*(d - e) + I*d
tolerance: 0.5%

### What output does it compute before clamping?

::: misses
- [K*d + I*d] The velocity form adds a change to the last output.
- [any] $u_{k-1} + K_p(e_k - e_{k-1}) + K_iTe_k$.
:::
:::
:::

::: check
kind: parts
given: t = 0.05 | 0.5 | 2; T = 1 | 10

## A loop must settle within {t} s (2%) and samples every {T} ms.

::: part
answer: exp(-4*T*1e-3/t)
tolerance: 0.5%

### Inside what radius must every closed-loop pole lie?

::: misses
- [any] $e^{-\sigma T}$ with σ = 4/$t_s$.
:::
:::
:::

::: check
kind: choice

## Why does the velocity form of a PI controller avoid integrator windup when its output is clamped?

- [ ] It has no integral action
- [x] It computes each new output as a change from the previous output actually applied, which is the clamped value, so no excess integral accumulates while the actuator is saturated
- [ ] It runs at a higher rate
- [ ] Clamping isn't needed with it

::: misses
- [1] Its $K_iTe_k$ term is the integral action.
- [3] Rate doesn't matter.
- [4] The clamp is what keeps it consistent with the actuator.
:::
:::

::: check
kind: derivation
vars: z = 0.2..0.95, w = 1..100, T = 0.0001..0.01

## Continuous poles with damping z and natural frequency w are sampled every T.

::: step
answer: 2*exp(-z*w*T)*cos(w*sqrt(1 - z^2)*T)

### What is minus the coefficient of z in the discrete polynomial?
:::

::: step
answer: exp(-2*z*w*T)

### What is its constant term?
:::

::: right
Right. The pair maps to a radius $e^{-\zeta\omega_nT}$ and angles $\pm\omega_dT$.
:::
:::

::: check
kind: python

## Write `pi_position(errors, Kp, KiT, umin, umax)` (integral summed separately, output clamped) and `pi_velocity(errors, Kp, KiT, umin, umax)` (each output the clamped previous output plus the change), both starting from zero output, zero integral and zero previous error, returning the list of outputs.

```python starter
def pi_position(errors, Kp, KiT, umin, umax):
    return [0.0] * len(errors)

def pi_velocity(errors, Kp, KiT, umin, umax):
    return [0.0] * len(errors)
```

```python solution
def pi_position(errors, Kp, KiT, umin, umax):
    out, integ = [], 0.0
    for e in errors:
        integ += KiT * e
        out.append(min(umax, max(umin, Kp * e + integ)))
    return out

def pi_velocity(errors, Kp, KiT, umin, umax):
    out, u, last = [], 0.0, 0.0
    for e in errors:
        u = min(umax, max(umin, u + Kp * (e - last) + KiT * e))
        last = e
        out.append(u)
    return out
```

```python tests
import random
r = random.Random(1)
es = [r.uniform(-1, 1) for _ in range(200)]
a, b = pi_position(es, 0.5, 0.1, -1e9, 1e9), pi_velocity(es, 0.5, 0.1, -1e9, 1e9)
assert max(abs(x - y) for x, y in zip(a, b)) < 1e-9, "Unsaturated, the two forms agree."
es = [1.0] * 50 + [-1.0] * 50
p, v = pi_position(es, 0.5, 0.1, -1, 1), pi_velocity(es, 0.5, 0.1, -1, 1)
assert p[50] == 1 and abs(v[50] + 0.1) < 1e-12, "At the switch the position form is still saturated; the velocity form reverses."
assert p[83] == 1 and p[86] < 1, "The position form stays saturated about 35 more samples, until its integral unwinds."
```

::: right
Right. The two forms are the same linear controller; they differ only in what they remember when the actuator can't follow.
:::
:::

::: explain
## Why does a digital controller's sample rate need to be many times its loop's crossover frequency, not just twice it?

::: model
The sampling theorem only says how fast to sample to reconstruct a signal, but a control loop also cares about delay. The zero-order hold that turns samples back into a continuous input delays them by about half a sample, and a controller that updates its output one sample after measuring adds a whole sample more. Delay costs phase margin in proportion to frequency, so at the crossover these delays eat roughly one and a half times the crossover frequency times the sample period in radians. Keeping that loss to a few degrees requires sampling tens of times faster than the crossover, and anti-aliasing filters add further lag, which is why the usual rule is 10 to 40 times the closed-loop bandwidth.
:::
:::

::: practice
::: check
given: z = 0.6 | 0.8; w = 10 | 40; T = 2 | 10
answer: exp(-z*w*T*1e-3)
tolerance: 0.5%

## Discrete pole radius for ζ = {z}, $\omega_n$ = {w}, T = {T} ms?

::: misses
- [any] $e^{-\zeta\omega_nT}$.
:::
:::

::: check
given: w = 50 | 300; f = 1 | 5
answer: 1.5*w/(f*1e3)*180/pi
unit: °
tolerance: 0.5%

## Phase lost at {w} rad/s sampling at {f} kHz with one sample of computation?

::: misses
- [any] $1.5\omega_cT$.
:::
:::

::: check
given: t = 0.1 | 1; T = 1 | 5
answer: exp(-4*T*1e-3/t)
tolerance: 0.5%

## Pole radius for 2% settling in {t} s at T = {T} ms?

::: misses
- [any] $e^{-4T/t_s}$.
:::
:::
:::
