---
title: Multirate lab
heading: Polyphase decimators and interpolators checked against direct filtering, and a windowed halfband design, in Python
eyebrow: S7 · Lesson 15 · Multirate lab
xp: 60
---

::: hook
Lessons 7 to 11 claimed that a polyphase decimator gives exactly the same output as filtering at the high rate and throwing samples away, that a polyphase interpolator equals zero-stuffing then filtering, and that a halfband filter has half its taps exactly zero and a response of exactly ½ at π/2. This lab writes each one out and checks it to rounding error, so the efficient versions can be trusted.
:::

::: play
- The curve is the magnitude response of a 23-tap halfband lowpass designed by windowing a half-band sinc with a Hamming window.
- It passes exactly ½ at ω = π/2, and its response is antisymmetric about that point: $H(\omega) + H(\pi - \omega) = 1$.
- Every tap an even distance from the center, except the center itself, is exactly zero.
:::

```sim plot
view: graph
x: w = 0..1
y: H = 0..1.1
plot: abs(0.5 + 2*(0.312379*cos(pi*w) - 0.089258*cos(3*pi*w) + 0.038545*cos(5*pi*w) - 0.015866*cos(7*pi*w) + 0.005412*cos(9*pi*w) - 0.002315*cos(11*pi*w))) | label: 23-tap halfband
```

::: predict
## A 13-tap FIR decimates 60 samples by 3, once directly (filter everything, keep every third output) and once in polyphase form. How closely do the outputs agree?

- [ ] Within 1%: polyphase is an approximation
- [x] To rounding error, about 10⁻¹⁵: they compute the same sums in a different order
- [ ] They differ by a delay of one sample
- [ ] Only the first output agrees

::: reveal
The polyphase form splits h into $E_p[j] = h[p + jM]$ and computes only the outputs that survive downsampling, from the same products. In double precision the two agree to about 9 × 10⁻¹⁶.
:::
:::

::: nameit
## What the lab computes

- **Decimation by M**: direct, $y[m] = \sum_kh[k]x[mM - k]$ computed for all n and kept at n = mM; polyphase, the same sum split as $\sum_{p=0}^{M-1}\sum_jh[p + jM]\,x[mM - p - jM]$.
- **Interpolation by L**: direct, zero-stuff then filter; polyphase, output sample n = mL + p uses only subfilter p: $y[mL + p] = \sum_jh[p + jL]\,x[m - j]$.
- **Halfband design**: $h[n] = \frac{\sin(\pi(n - c)/2)}{\pi(n - c)}w[n]$ with $h[c] = \frac12$, c = (N − 1)/2 and a Hamming window; for N = 4K − 1 the taps at even nonzero offsets from c vanish exactly.
:::

::: check
kind: python

## Write `decim_direct(x, h, M)` and `decim_poly(x, h, M)`: an FIR decimator computed both ways (zero initial state; output m corresponds to input index mM).

```python starter
def decim_direct(x, h, M):
    return x[::M]

def decim_poly(x, h, M):
    return x[::M]
```

```python solution
def decim_direct(x, h, M):
    y = [sum(h[k] * x[n - k] for k in range(len(h)) if 0 <= n - k < len(x)) for n in range(len(x))]
    return y[::M]

def decim_poly(x, h, M):
    out = []
    for m in range(0, len(x), M):
        s = 0.0
        for p in range(M):
            j = 0
            while p + j * M < len(h):
                n = m - p - j * M
                if 0 <= n < len(x):
                    s += h[p + j * M] * x[n]
                j += 1
        out.append(s)
    return out
```

```python tests
import random
r = random.Random(1)
x = [r.gauss(0, 1) for _ in range(60)]
h = [r.gauss(0, 1) for _ in range(13)]
a, b = decim_direct(x, h, 3), decim_poly(x, h, 3)
assert abs(a[1] - sum(h[k] * x[3 - k] for k in range(4))) < 1e-12, "Output 1 is the filter evaluated at input index 3."
assert len(a) == len(b) == 20 and max(abs(u - v) for u, v in zip(a, b)) < 1e-12, "Polyphase equals direct to rounding error."
```

::: right
Right. The polyphase version does a third of the multiplications for the same outputs.
:::
:::

::: check
kind: python

## Write `interp_direct(x, h, L)` (zero-stuff by L, then filter) and `interp_poly(x, h, L)` (each output n = mL + p from subfilter p).

```python starter
def interp_direct(x, h, L):
    return x

def interp_poly(x, h, L):
    return x
```

```python solution
def interp_direct(x, h, L):
    up = [0.0] * (len(x) * L)
    for i, v in enumerate(x):
        up[i * L] = v
    return [sum(h[k] * up[n - k] for k in range(len(h)) if 0 <= n - k) for n in range(len(up))]

def interp_poly(x, h, L):
    out = []
    for n in range(len(x) * L):
        p, m = n % L, n // L
        s, j = 0.0, 0
        while p + j * L < len(h):
            if 0 <= m - j < len(x):
                s += h[p + j * L] * x[m - j]
            j += 1
        out.append(s)
    return out
```

```python tests
import random
r = random.Random(1)
x = [r.gauss(0, 1) for _ in range(60)]
h = [r.gauss(0, 1) for _ in range(13)]
a, b = interp_direct(x, h, 4), interp_poly(x, h, 4)
assert len(a) == len(b) == 240 and max(abs(u - v) for u, v in zip(a, b)) < 1e-12, "Polyphase interpolation equals zero-stuffing and filtering."
```

::: right
Right. Three quarters of the zero-stuffed products are multiplications by zero; polyphase never computes them.
:::
:::

::: check
kind: python

## Write `halfband(N)`: the Hamming-windowed half-band sinc of odd length N (center value ½), and `response(h, w)`: |H(e^{jω})|.

```python starter
def halfband(N):
    return [0.0] * N

def response(h, w):
    return 0.0
```

```python solution
import cmath, math

def halfband(N):
    c = (N - 1) / 2
    h = []
    for n in range(N):
        t = n - c
        s = 0.5 if t == 0 else math.sin(math.pi * t / 2) / (math.pi * t)
        h.append(s * (0.54 - 0.46 * math.cos(2 * math.pi * n / (N - 1))))
    return h

def response(h, w):
    return abs(sum(v * cmath.exp(-1j * w * n) for n, v in enumerate(h)))
```

```python tests
import math
h = halfband(23)
assert all(abs(h[n]) < 1e-15 for n in range(1, 23, 2) if n != 11), "Every tap an even distance from the center is zero."
assert abs(response(h, math.pi / 2) - 0.5) < 1e-12, "Exactly ½ at π/2."
assert abs(response(h, 0) + response(h, math.pi) - 1) < 1e-12, "H(0) + H(π) = 1."
assert abs(response(h, 0) - 0.9978) < 1e-4, "Passband gain 0.998 with this window."
```

::: right
Right. The zeros come from sin(πt/2) vanishing at even t, so they survive any window.
:::
:::

::: explain
## Why is a polyphase implementation exactly equivalent to filtering at the high rate, rather than an approximation?

::: model
A decimator only keeps every Mth output of its filter, and each of those outputs is a fixed sum of products of filter taps with input samples. Grouping the taps by their index modulo M, the polyphase components, and the input samples correspondingly, gives exactly the same products, just added in a different order; the outputs that would be discarded are simply never computed. The noble identities guarantee this rearrangement is exact for any filter. The only difference in practice is rounding, since floating-point addition in a different order can differ in the last bit.
:::
:::
