---
title: Filter analysis lab
heading: Frequency response from any transfer function, group delay, filter order for any specification, Sallen-Key design and noise bandwidth, in Python
eyebrow: C4 · Lesson 22 · Filter analysis lab
xp: 50
---

::: hook
Lessons 1 to 21 built filters from formulas: each response type had its own expression for gain, order, delay or noise bandwidth. A filter tool doesn't keep a separate formula for every case. It evaluates the transfer function as a ratio of polynomials in s, and gets everything else by numerical calculus: group delay by differentiating the phase, noise bandwidth by integrating the gain. In this lab you'll write those general tools and check them against the special formulas, then use them to size filters and design a Sallen-Key stage.
:::

::: play
- The curves are the stopband attenuation of a Butterworth and a Chebyshev filter of the same order, from the passband edge out to ten times it, on a log frequency axis.
- The Chebyshev trades passband ripple for a much faster fall just past the edge. Raise the ripple and the gap widens; raise the order and both steepen.
- The readouts give each filter's attenuation at twice the edge. Step 3 turns a specification into the order each type needs.
:::

```sim plot
view: graph
x: x = 1..10 log
y: a = 0..150 dB
slider: n = 2..8 step 1 = 4
slider: r = 0.1..3 step 0.1 = 1 dB
plot: 10*log(1 + x^(2*n)) | label: Butterworth attenuation | samples: 300
plot: 10*log(1 + (10^(r/10) - 1)*cosh(n*ln(x + sqrt(x^2 - 1)))^2) | color: ch2 | label: Chebyshev attenuation | samples: 300
readout: Butterworth at 2× the edge, dB = 10*log(1 + 2^(2*n)) | digits: 4
readout: Chebyshev at 2× the edge, dB = 10*log(1 + (10^(r/10) - 1)*cosh(n*ln(2 + sqrt(3)))^2) | digits: 4
```

::: predict
## A low-pass must lose at most 1 dB up to its passband edge and at least 40 dB at five times that frequency. Which needs fewer poles, a Butterworth or a Chebyshev?

- [ ] The Butterworth: 3 against 4
- [x] The Chebyshev: 3 against 4
- [ ] They need the same order
- [ ] It depends on the component values

::: reveal
The Chebyshev: order 3 (2.61 rounded up) against the Butterworth's 4 (3.28 rounded up). The Chebyshev spends the whole 1 dB allowance as ripple across the passband, and in return falls faster right past the edge. Step 3 computes both from the specification.
:::
:::

::: nameit
## Transfer functions as polynomials

A filter's transfer function is a ratio of polynomials in s, $H(s) = \frac{b_0s^m + \cdots + b_m}{a_0s^n + \cdots + a_n}$. Setting $s = j2\pi f$ and evaluating both polynomials (NumPy's `polyval` does it) gives H(f) at any frequency: magnitude in dB, $20\log|H|$, and phase from its angle.

## Group delay numerically

Group delay is $\tau_g = -\frac{d\phi}{d\omega}$. Computed from an unwrapped phase on a fine grid with central differences, it matches the closed forms, such as $\frac{2\tau}{1 + (\omega\tau)^2}$ for a first-order all-pass, to the grid's accuracy.

## Order from a specification

For passband ripple $r_p$ dB, stopband attenuation $r_s$ dB, and stopband-to-passband frequency ratio x:

$$n_{Butterworth} = \frac{\log\frac{10^{r_s/10} - 1}{10^{r_p/10} - 1}}{2\log x}, \qquad n_{Chebyshev} = \frac{\text{arccosh}\sqrt{\frac{10^{r_s/10} - 1}{10^{r_p/10} - 1}}}{\text{arccosh}\,x},$$

each rounded up. The Chebyshev's arccosh grows more slowly than a logarithm's denominator, which is why it needs fewer poles.

## Sallen-Key

A unity-gain Sallen-Key low-pass has $f_0 = \frac{1}{2\pi\sqrt{R_1R_2C_1C_2}}$ and $Q = \frac{\sqrt{R_1R_2C_1C_2}}{C_2(R_1 + R_2)}$. Its transfer function, $\frac{1}{R_1R_2C_1C_2s^2 + C_2(R_1 + R_2)s + 1}$, can be fed to the general tools to confirm both.

## Noise bandwidth numerically

The equivalent noise bandwidth is $\frac{1}{|H(0)|^2}\int_0^\infty|H(f)|^2df$, the width of a brick wall passing the same noise. Integrating numerically reproduces $\frac\pi2f_0$ for one pole and $\frac{\pi}{2\sqrt2}f_0$ = 1.111f₀ for a second-order Butterworth.
:::

::: example
## A filter must stay within 1 dB to its edge and be 40 dB down at five times the edge. What order does each type need?

::: solution
1. **The common ratio.** The ratio inside both formulas is
   $$\frac{10^4 - 1}{10^{0.1} - 1} = 3.86 \times 10^4$$
2. **Butterworth.**
   $$\begin{aligned} n &= \frac{\log(3.86 \times 10^4)}{2\log5} \\ &= 3.28 \to 4 \end{aligned}$$
3. **Chebyshev.**
   $$\begin{aligned} n &= \frac{\text{arccosh}\sqrt{3.86 \times 10^4}}{\text{arccosh}\,5} \\ &= \frac{5.97}{2.29} \\ &= 2.61 \to 3 \end{aligned}$$
4. **A tighter specification.** A tighter specification, 0.5 dB and 60 dB at twice the edge, needs 12 Butterworth poles but only 7 Chebyshev ones.
5. **When it pays.** That's when the extra design effort of a Chebyshev, or an elliptic, pays.

**Answer:** a Butterworth needs order 4 and a Chebyshev order 3.
:::
:::

::: example
## A unity-gain Sallen-Key stage has $R_1 = R_2$ = 10 kΩ, $C_1$ = 22 nF and $C_2$ = 10 nF. Find f₀ and Q, and confirm them from its transfer function.

::: solution
1. **Natural frequency.**
   $$\begin{aligned} f_0 &= \frac{1}{2\pi\sqrt{10^8 \times 2.2 \times 10^{-16}}} \\ &= 1073\ \text{Hz} \end{aligned}$$
2. **Q.**
   $$\begin{aligned} Q &= \frac{\sqrt{10^8 \times 2.2 \times 10^{-16}}}{10^{-8} \times 2 \times 10^4} \\ &= 0.742 \end{aligned}$$
3. **The transfer function.** It's $H = 1/D$, with
   $$\begin{aligned} D &= (2.2 \times 10^{-8})s^2 \\ &\quad + (2 \times 10^{-4})s + 1 \end{aligned}$$
4. **Evaluate it at $f_0$.** At $j2\pi \times 1073$ it gives |H| = 0.742 and a phase of exactly −90°, as a second-order low-pass has at its natural frequency: two independent checks.

**Answer:** $f_0$ = 1073 Hz and Q = 0.742, confirmed by |H| = 0.742 and a −90° phase at 1073 Hz.
:::
:::

::: example
## Compute the noise bandwidths of first- and second-order Butterworth low-passes with a 1 kHz corner by numerical integration.

::: solution
1. **One pole.** For one pole,
   $$|H|^2 = \frac{1}{1 + (f/f_0)^2}$$
2. **Integrate it.** Integrating to a large multiple of $f_0$, and adding the analytic tail beyond it, gives
   $$\begin{aligned} B_n &= 1571\ \text{Hz} \\ &= \frac\pi2f_0 \end{aligned}$$
3. **Two poles.** For two poles,
   $$|H|^2 = \frac{1}{1 + (f/f_0)^4}$$
   integrates to 1111 Hz.
4. **Any response.** The numerical method doesn't care what the filter is: an elliptic filter with stopband ripple, or a measured response, integrates the same way. That's how converter datasheets quote noise for their digital filters.

**Answer:** 1571 Hz for one pole and 1111 Hz for two.
:::
:::

::: check
kind: python

## Step 1. Write `freqresp(num, den, f)` returning `(mag_db, phase_deg)` arrays for $H(s) = \frac{\text{num}(s)}{\text{den}(s)}$ (coefficient lists, highest power first) at frequencies f.

```python starter
import numpy as np

def freqresp(num, den, f):
    f = np.asarray(f, float)
    return np.zeros_like(f), np.zeros_like(f)

print(freqresp([1], [1e-3, 1], [159.155]))
```

```python solution
import numpy as np

def freqresp(num, den, f):
    s = 2j * np.pi * np.asarray(f, float)
    H = np.polyval(num, s) / np.polyval(den, s)
    return 20 * np.log10(np.abs(H)), np.degrees(np.angle(H))

print(freqresp([1], [1e-3, 1], [159.155]))
```

```python tests
import numpy as np
m, p = freqresp([1], [1e-3, 1], [1000 / (2 * np.pi)])
assert abs(m[0] + 3.0103) < 1e-3 and abs(p[0] + 45) < 1e-6, "An RC low-pass with τ = 1 ms is −3 dB and −45° at 159 Hz."
m2, p2 = freqresp([1, 0], [1, 1000], [1000 / (2 * np.pi)])
assert abs(m2[0] + 3.0103) < 1e-3 and abs(p2[0] - 45) < 1e-6, "The matching high-pass leads by 45° there."
```

::: right
Right. Two polynomial evaluations give any linear filter's response.
:::
:::

::: check
kind: python

## Step 2. Write `group_delay(num, den, f)` returning the group delay in seconds at frequencies f, from a central difference of the unwrapped phase on a fine grid around each point.

```python starter
import numpy as np

def group_delay(num, den, f):
    return np.zeros(len(np.atleast_1d(f)))

print(group_delay([-1e-3, 1], [1e-3, 1], [1.0, 159.155]))
```

```python solution
import numpy as np

def phase(num, den, f):
    s = 2j * np.pi * np.asarray(f, float)
    return np.unwrap(np.angle(np.polyval(num, s) / np.polyval(den, s)))

def group_delay(num, den, f):
    f = np.atleast_1d(np.asarray(f, float))
    out = []
    for fc in f:
        df = max(fc, 1.0) * 1e-5
        ph = phase(num, den, [fc - df, fc, fc + df])
        out.append(-(ph[2] - ph[0]) / (2 * 2 * np.pi * df))
    return np.array(out)

print(group_delay([-1e-3, 1], [1e-3, 1], [1.0, 159.155]))
```

```python tests
import numpy as np
gd = group_delay([-1e-3, 1], [1e-3, 1], [0.01, 1000 / (2 * np.pi)])
assert abs(gd[0] - 2e-3) < 1e-8, f"A first-order all-pass with τ = 1 ms delays 2 ms at DC; got {gd[0]}"
assert abs(gd[1] - 1e-3) < 1e-8, f"It delays 1 ms at ω = 1/τ; got {gd[1]}"
g1 = group_delay([1], [1e-3, 1], [0.01])
assert abs(g1[0] - 1e-3) < 1e-8, "An RC low-pass delays τ at low frequency."
```

::: right
Right. Unwrapping the phase first keeps the derivative from jumping at ±180°.
:::
:::

::: check
kind: python

## Step 3. Write `orders(rp, rs, x)` returning `(n_butterworth, n_chebyshev)` as integers, the smallest orders that meet passband ripple `rp` dB and stopband attenuation `rs` dB at frequency ratio `x`.

```python starter
def orders(rp, rs, x):
    return 1, 1

print(orders(1, 40, 5))
```

```python solution
import math

def orders(rp, rs, x):
    k = (10 ** (rs / 10) - 1) / (10 ** (rp / 10) - 1)
    nb = math.log10(k) / (2 * math.log10(x))
    nc = math.acosh(math.sqrt(k)) / math.acosh(x)
    return math.ceil(nb - 1e-12), math.ceil(nc - 1e-12)

print(orders(1, 40, 5))
```

```python tests
assert orders(1, 40, 5) == (4, 3), f"1 dB and 40 dB at 5× need Butterworth 4, Chebyshev 3; got {orders(1, 40, 5)}"
assert orders(0.5, 60, 2) == (12, 7), "0.5 dB and 60 dB at 2× need 12 and 7."
assert orders(3.0103, 60, 10)[0] == 3, "A Butterworth 3 dB down at its edge reaches 60 dB at ten times with order 3."
```

::: right
Right. The tighter the transition band, the more the Chebyshev saves.
:::
:::

::: check
kind: python

## Step 4. Write `sallen_key(R1, R2, C1, C2)` returning `(f0, Q)` from the formulas, and `sk_check(R1, R2, C1, C2)` returning `(|H|, phase_deg)` at f0 from the transfer function $\frac{1}{R_1R_2C_1C_2s^2 + C_2(R_1 + R_2)s + 1}$.

```python starter
def sallen_key(R1, R2, C1, C2):
    return 1000.0, 0.707

def sk_check(R1, R2, C1, C2):
    return 0.707, -90.0

print(sallen_key(1e4, 1e4, 22e-9, 10e-9))
```

```python solution
import numpy as np

def sallen_key(R1, R2, C1, C2):
    m = np.sqrt(R1 * R2 * C1 * C2)
    return float(1 / (2 * np.pi * m)), float(m / (C2 * (R1 + R2)))

def sk_check(R1, R2, C1, C2):
    f0, _ = sallen_key(R1, R2, C1, C2)
    s = 2j * np.pi * f0
    H = 1 / (R1 * R2 * C1 * C2 * s * s + C2 * (R1 + R2) * s + 1)
    return float(abs(H)), float(np.degrees(np.angle(H)))

print(sallen_key(1e4, 1e4, 22e-9, 10e-9))
```

```python tests
f0, Q = sallen_key(1e4, 1e4, 22e-9, 10e-9)
assert abs(f0 - 1073.02) < 0.05 and abs(Q - 0.74162) < 1e-4, f"Expected 1073 Hz and Q = 0.742; got {f0}, {Q}"
m, p = sk_check(1e4, 1e4, 22e-9, 10e-9)
assert abs(m - Q) < 1e-9 and abs(p + 90) < 1e-9, "At f0 the gain equals Q and the phase is −90°."
```

::: right
Right. The formula and the transfer function agree, which checks both.
:::
:::

::: check
kind: python

## Step 5. Write `enbw(order, f0)` returning the noise bandwidth of a Butterworth low-pass, $|H|^2 = \frac{1}{1 + (f/f_0)^{2n}}$, by integrating numerically from 0 to 1000f₀ and adding the tail beyond analytically.

```python starter
def enbw(order, f0):
    return f0

print(enbw(1, 1000), enbw(2, 1000))
```

```python solution
import numpy as np

def enbw(order, f0):
    f = np.linspace(0, 1000 * f0, 2000001)
    y = 1 / (1 + (f / f0) ** (2 * order))
    trap = np.trapezoid if hasattr(np, "trapezoid") else np.trapz
    tail = f0 * 1000 ** (1 - 2 * order) / (2 * order - 1)
    return float(trap(y, f) + tail)

print(enbw(1, 1000), enbw(2, 1000))
```

```python tests
import math
assert abs(enbw(1, 1000) - math.pi / 2 * 1000) < 0.5, f"One pole: π/2 × f0 = 1571 Hz; got {enbw(1, 1000)}"
assert abs(enbw(2, 1000) - math.pi / (2 * math.sqrt(2)) * 1000) < 0.5, f"Two poles: 1111 Hz; got {enbw(2, 1000)}"
assert abs(enbw(4, 1000) - 1000 * (math.pi / 8) / math.sin(math.pi / 8)) < 0.5, "Four poles: about 1026 Hz."
```

::: right
Right. The tail matters most for one pole, whose $|H|^2$ falls only as $1/f^2$.
:::
:::

::: check
kind: parts
given: p = 0.5 | 1 | 3; s = 40 | 60; x = 2 | 4

## A low-pass may ripple {p} dB in its passband and must be {s} dB down at {x} times its edge.

::: part
answer: log((10^(s/10) - 1)/(10^(p/10) - 1))/(2*log(x))
tolerance: 0.5%

### What Butterworth order does that take, before rounding up?

::: misses
- [any] $\frac{\log K}{2\log x}$ with $K = \frac{10^{r_s/10} - 1}{10^{r_p/10} - 1}$.
:::
:::

::: part
answer: ln(sqrt((10^(s/10) - 1)/(10^(p/10) - 1)) + sqrt((10^(s/10) - 1)/(10^(p/10) - 1) - 1))/ln(x + sqrt(x^2 - 1))
tolerance: 0.5%

### And a Chebyshev?

::: misses
- [any] $\frac{\text{arccosh}\sqrt K}{\text{arccosh}\,x}$.
:::
:::
:::

::: check
kind: parts
given: a = 4.7 | 10; b = 10 | 22; c = 2.2 | 4.7

## A unity-gain Sallen-Key low-pass has $R_1 = R_2$ = {a} kΩ, $C_1$ = {b} nF and $C_2$ = {c} nF.

::: part
answer: 1/(2*pi*a*1e3*sqrt(b*c)*1e-9)
unit: Hz
tolerance: 0.5%

### What's f₀?

::: misses
- [any] $\frac{1}{2\pi R\sqrt{C_1C_2}}$.
:::
:::

::: part
answer: sqrt(b/c)/2
tolerance: 0.5%

### What's Q?

::: misses
- [any] $\frac12\sqrt{C_1/C_2}$.
:::
:::
:::

::: check
given: n = 1 | 2 | 3 | 6; f = 1 | 20
answer: f*(pi/(2*n))/sin(pi/(2*n))
unit: kHz
tolerance: 0.5%

## What's the noise bandwidth of an order-{n} Butterworth low-pass with a {f} kHz corner?

::: right
Right. $f_0\frac{\pi/2n}{\sin(\pi/2n)}$, approaching $f_0$ as the order grows.
:::

::: misses
- [f] Only a brick wall's noise bandwidth equals its corner.
- [any] $f_0\frac{\pi/2n}{\sin(\pi/2n)}$.
:::
:::

::: check
given: t = 0.1 | 1 | 10; w = 0.5 | 1 | 3
answer: 2*t/(1 + w^2)
unit: ms
tolerance: 0.5%

## A first-order all-pass has τ = {t} ms. What's its group delay at ω = {w}/τ?

::: right
Right. $\frac{2\tau}{1 + (\omega\tau)^2}$.
:::

::: misses
- [t/(1 + w^2)] An all-pass delays twice as much as a single pole.
- [any] $\frac{2\tau}{1 + (\omega\tau)^2}$.
:::
:::

::: explain
## Why do filter tools compute group delay and noise bandwidth numerically instead of using formulas?

::: model
Formulas exist only for idealized cases: a single pole, a Butterworth of a given order, a first-order all-pass. A real filter design mixes sections, uses rounded component values, or comes from a measurement, and its transfer function doesn't match any textbook form exactly. But every linear filter's response can be evaluated at any frequency from its transfer function, and group delay and noise bandwidth are just a derivative and an integral of that response. Computing them numerically works for every filter at once, and checking the numbers against the known formulas on simple cases is how you trust the tool on the complicated ones.
:::
:::

::: practice

::: check
given: n = 2 | 5; f = 5 | 50
answer: f*(pi/(2*n))/sin(pi/(2*n))
unit: kHz
tolerance: 0.5%

## Noise bandwidth of an order-{n} Butterworth at {f} kHz?

::: misses
- [any] $f_0\frac{\pi/2n}{\sin(\pi/2n)}$.
:::
:::

::: check
given: a = 2.2 | 15; b = 6.8 | 33; c = 1 | 3.3
answer: sqrt(b/c)/2
tolerance: 0.5%

## Q of an equal-R Sallen-Key with $C_1$ = {b} nF, $C_2$ = {c} nF?

::: misses
- [any] $\frac12\sqrt{C_1/C_2}$.
:::
:::
:::
