---
title: DSP hardware lab
heading: A fixed-point FIR, a CIC decimator in wrapping arithmetic, and CORDIC, bit-exact in Python
eyebrow: S3 · Lesson 35 · DSP hardware lab
xp: 60
---

::: hook
DSP hardware is specified in floating point and built in fixed point, and the gap between them is where bugs live: coefficients that round to the wrong value, accumulators that overflow, rounding that biases the output. This lab writes bit-exact models of three classic blocks from lesson 31 and checks each against an exact reference: a Q1.15 FIR filter, a CIC decimator whose registers are allowed to wrap, and a CORDIC rotator that computes sines and cosines with shifts and adds.
:::

::: play
- The line is CORDIC's worst error computing a cosine after n iterations, about $2^{-(n-1)}$: one more bit per iteration.
- The dashed line is the error of a Q1.15 number's rounding, $2^{-16}$: about 17 iterations match it.
- Each iteration costs two shift-and-adds and a small table lookup, so a 16-bit CORDIC is 16 adder delays or 16 pipeline stages.
:::

```sim plot
view: graph
x: n = 4..32
y: e = 1e-10..0.1 log
samples: 29
plot: 2^(-(n - 1)) | stems | label: CORDIC error bound
plot: 2^(-16) + 0*n | dashed | label: Q1.15 rounding
```

::: predict
## A CIC decimator with 3 stages and R = 8 takes 12-bit samples. Its integrators overflow and wrap around constantly. Does the output come out right?

- [x] Yes, if every register has 12 + 3 log₂8 = 21 bits: two's complement wrapping cancels in the combs
- [ ] No: integrators must never overflow
- [ ] Only if the input is always positive
- [ ] Yes, with any register width

::: reveal
The integrators compute running sums modulo $2^B$, and the combs take differences of those sums, which are exact modulo $2^B$ as well. As long as the true output fits in B bits, the wrapped arithmetic gives exactly the right answer. With B = 21 the output's range $2^{12} \times 8^3$ fits; with 19 bits it doesn't, and the output is wrong. The lab shows both.
:::
:::

::: nameit
## The blocks

- **Q1.15 FIR:** quantize coefficients with rounding, $\lfloor 2^{15}h + 0.5\rfloor$; multiply-accumulate 16-bit samples into a wide accumulator exactly; round back to Q1.15 by adding $2^{14}$ and shifting right 15. The error against exact arithmetic is under about one LSB.
- **CIC:** M integrators $y \mathrel{+}= x$ at the input rate, keep every Rth value, then M combs $y = x - x_\text{prev}$; registers of $B_\text{in} + M\log_2R$ bits, all arithmetic modulo $2^B$. The result equals filtering by the moving average of length R applied M times, without dividing.
- **CORDIC (rotation mode):** starting from (1, 0) with angle z, each step i rotates by $\pm\arctan2^{-i}$ toward z = 0 using $x \mathrel{-}= d\,y\,2^{-i}$ and $y \mathrel{+}= d\,x\,2^{-i}$; the vector grows by $K = \prod\sqrt{1 + 2^{-2i}} \approx 1.64676$, divided out at the end (or folded into the starting vector).
:::

::: check
kind: python

## Write `q15(h)`: round coefficients to Q1.15 integers (clamped to −32768..32767), and `fir_fixed(x, hq)`: filter Q1.15 integer samples with integer coefficients, accumulating exactly and rounding each output back to Q1.15 (add $2^{14}$, shift right 15).

```python starter
def q15(h):
    return [0 for c in h]

def fir_fixed(x, hq):
    return [0 for v in x]
```

```python solution
import math

def q15(h):
    return [max(-32768, min(32767, math.floor(c * 32768 + 0.5))) for c in h]

def fir_fixed(x, hq):
    y = []
    for n in range(len(x)):
        acc = 0
        for k, c in enumerate(hq):
            if n - k >= 0:
                acc += c * x[n - k]
        y.append((acc + (1 << 14)) >> 15)
    return y
```

```python tests
import math, random
h = [0.1, 0.2, 0.4, 0.2, 0.1]
assert q15(h) == [3277, 6554, 13107, 6554, 3277], "0.1 × 32768 = 3276.8 rounds to 3277."
r = random.Random(1)
x = [math.floor(r.uniform(-0.5, 0.5) * 32768 + 0.5) for _ in range(500)]
y = fir_fixed(x, q15(h))
exact = [sum(h[k] * x[n - k] for k in range(5) if n - k >= 0) for n in range(500)]
assert max(abs(a - b) for a, b in zip(y, exact)) <= 1.2, "Within about one LSB of exact arithmetic."
```

::: right
Right. Exact accumulation and a single rounding at the end keep the error near one LSB, whatever the number of taps.
:::
:::

::: check
kind: python

## Write `cic(x, M, R, B)`: an M-stage CIC decimator by R on integer samples, with every register B bits wide and wrapping (two's complement), returning the output samples as signed integers (one per R inputs, taken after inputs R − 1, 2R − 1, …).

```python starter
def cic(x, M, R, B):
    return []
```

```python solution
def cic(x, M, R, B):
    mask = (1 << B) - 1
    ints, combs, out = [0] * M, [0] * M, []
    for i, v in enumerate(x):
        s = v
        for j in range(M):
            ints[j] = (ints[j] + s) & mask
            s = ints[j]
        if (i + 1) % R == 0:
            for j in range(M):
                prev = combs[j]
                combs[j] = s
                s = (s - prev) & mask
            out.append(s - (1 << B) if s >= 1 << (B - 1) else s)
    return out
```

```python tests
import random
def ref(x, M, R):
    h = [1]
    for _ in range(M):
        nh = [0] * (len(h) + R - 1)
        for i, a in enumerate(h):
            for j in range(R):
                nh[i + j] += a
        h = nh
    y = [sum(h[k] * x[n - k] for k in range(len(h)) if n - k >= 0) for n in range(len(x))]
    return [y[n] for n in range(R - 1, len(x), R)]
r = random.Random(4)
x = [r.randrange(-2048, 2048) for _ in range(256)]
assert cic(x, 3, 8, 21) == ref(x, 3, 8), "21 bits: exact, despite the wrapping."
assert cic(x, 3, 8, 19) != ref(x, 3, 8), "19 bits: the output itself doesn't fit."
```

::: right
Right. Wrapping is harmless in the integrators because the combs' differences undo it; only the final result's range sets the width.
:::
:::

::: check
kind: python

## Write `cordic(theta, n)`: rotate (1, 0) toward angle theta (|theta| < 1.5) with n CORDIC iterations and return (cos, sin) after dividing out the gain, and the gain K.

```python starter
import math

def cordic(theta, n):
    return (1.0, 0.0, 1.0)
```

```python solution
import math

def cordic(theta, n):
    x, y, z, K = 1.0, 0.0, theta, 1.0
    for i in range(n):
        d = 1 if z >= 0 else -1
        x, y = x - d * y * 2.0 ** -i, y + d * x * 2.0 ** -i
        z -= d * math.atan(2.0 ** -i)
        K *= math.sqrt(1 + 2.0 ** (-2 * i))
    return (x / K, y / K, K)
```

```python tests
import math
for n in (8, 16, 24):
    err = max(max(abs(cordic(t, n)[0] - math.cos(t)), abs(cordic(t, n)[1] - math.sin(t))) for t in [i * 0.01 - 1.5 for i in range(300)])
    assert err < 2.0 ** -(n - 1), "About one bit per iteration."
assert abs(cordic(0.3, 24)[2] - 1.6467602) < 1e-6, "The CORDIC gain: 1.64676."
```

::: right
Right. The gain is the same for every angle, so hardware folds 1/K into the starting vector and never divides.
:::
:::

::: explain
## Why can a CIC filter's integrators overflow without corrupting its output?

::: model
Two's complement arithmetic with B bits is arithmetic modulo $2^B$: sums and differences are exact except for multiples of $2^B$. The integrators accumulate running sums that wrap around many times, and the combs then subtract one wrapped running sum from an earlier one. The difference of two values that are each correct modulo $2^B$ is also correct modulo $2^B$, so the wraps cancel. If the true output is guaranteed to fit within the B-bit range, which sets $B = B_\text{in} + M\log_2R$, the value that remains modulo $2^B$ is exactly the true output.
:::
:::
