---
title: "Lab: Fourier series in code"
heading: Coefficients, synthesis, Gibbs and Parseval by computer
eyebrow: A10 · Lesson 5 · Lab: Fourier series in code
xp: 60
---

::: hook
Lessons 1 to 4 found Fourier coefficients by integrating by hand. A computer does those integrals numerically for any waveform, including measured ones with no formula. In this lab you'll compute a square wave's coefficients, rebuild it from its harmonics and measure the Gibbs overshoot that never goes away, confirm Parseval's theorem by summing ten thousand terms, compute total harmonic distortion, and filter the square wave harmonic by harmonic.
:::

::: play
- The curve is the sum of a ±1 square wave's first $N$ odd harmonics, $\sum\frac{4}{\pi n}\sin(2\pi nt)$.
- Add harmonics: the edges sharpen and the ripple crowds toward them, but the first overshoot stays at about 9% of the jump.
- That's the Gibbs phenomenon: a finite sum can't follow a jump, and the overshoot's height doesn't shrink, only its width.
:::

```sim plot
view: graph
x: t = 0..1 s
y: x = -1.4..1.4
slider: N = 1..15 step 1 = 5
plot: 4/pi*(sin(2*pi*t) + step(N - 1.5)*sin(6*pi*t)/3 + step(N - 2.5)*sin(10*pi*t)/5 + step(N - 3.5)*sin(14*pi*t)/7 + step(N - 4.5)*sin(18*pi*t)/9 + step(N - 5.5)*sin(22*pi*t)/11 + step(N - 6.5)*sin(26*pi*t)/13 + step(N - 7.5)*sin(30*pi*t)/15 + step(N - 8.5)*sin(34*pi*t)/17 + step(N - 9.5)*sin(38*pi*t)/19 + step(N - 10.5)*sin(42*pi*t)/21 + step(N - 11.5)*sin(46*pi*t)/23 + step(N - 12.5)*sin(50*pi*t)/25 + step(N - 13.5)*sin(54*pi*t)/27 + step(N - 14.5)*sin(58*pi*t)/29) | label: partial sum | samples: 1600
plot: step(0.5 - t)*2 - 1 | dashed | color: ch2 | label: square wave | samples: 1600
readout: highest harmonic = 2*N - 1 | digits: 3
```

::: predict
## The partial sums of a ±1 square wave's series overshoot the jump. As you add more and more harmonics, the peak of the overshoot:

- [ ] Shrinks to zero
- [x] Stays near 1.18, about 9% of the 2 V jump above the top
- [ ] Grows without limit
- [ ] Disappears once there are more than 100 terms

::: reveal
It stays near 1.179. The overshoot moves closer to the jump and gets narrower, so the series still converges at every point away from the edge, but its height approaches $\frac{2}{\pi}\text{Si}(\pi) = 1.179$, about 9% of the jump above the flat top. Filters with sharp cutoffs ring the same way on step inputs, for the same reason.
:::
:::

::: nameit
## Coefficients by integration

For a period $T$ sampled finely, the sine coefficients are

$$b_n = \frac2T\int_0^Tx(t)\sin\frac{2\pi nt}{T}\,dt$$

and the trapezoid rule (`np.trapezoid`) evaluates the integral. For a measured waveform the same sum works on the samples, and that's what an FFT does efficiently for all $n$ at once.

## Synthesis

Adding $\sum b_n\sin(2\pi nt/T)$ up to $N$ terms rebuilds the waveform. Smooth waveforms converge quickly; ones with jumps converge slowly and show the Gibbs overshoot of about 9% of the jump.

## Power and distortion

Parseval's theorem: the mean square is $a_0^2 + \sum\frac{a_n^2 + b_n^2}{2}$. **Total harmonic distortion** compares everything above the fundamental with the fundamental:

$$\text{THD} = \frac{\sqrt{\sum_{n\ge2}A_n^2}}{A_1}$$

For a square wave it's $\sqrt{\frac{\pi^2}{8} - 1} = 48.3\%$.

## Filtering harmonic by harmonic

A linear filter multiplies each harmonic by $|H(nf_0)|$ and shifts its phase. Low-pass filtering a square wave cuts the higher harmonics more, rounding the corners.
:::

::: example
## A ±1 V square wave at 1 kHz passes through an RC low-pass with its corner at 1 kHz. How do the 3rd harmonic and the fundamental compare at the output?

::: solution
1. **At the input.** The 3rd harmonic is $\frac13$ of the fundamental.
2. **The filter's gains.** The filter passes the fundamental with gain $\frac{1}{\sqrt2}$ and the 3rd with $\frac{1}{\sqrt{10}}$.
3. **At the output.**
   $$\begin{aligned} \frac{V_3}{V_1} &= \frac13 \times \frac{1/\sqrt{10}}{1/\sqrt2} \\ &= \frac13\sqrt{0.2} \\ &= 0.149 \end{aligned}$$
   The output looks much more like a sine than the input does, though a single pole is a gentle filter.

**Answer:** at the output the 3rd harmonic is 0.149 of the fundamental, down from a third at the input.
:::
:::

::: example
## What is the THD of a ±1 square wave?

::: solution
1. **The harmonics.** They are $\frac{4}{\pi n}$ for odd $n$, and the total mean square is 1.
2. **The fundamental's share.**
   $$\begin{aligned} \frac12\left(\frac4\pi\right)^2 &= \frac{8}{\pi^2} \\ &= 0.811 \end{aligned}$$
3. **The harmonics' share.** The rest is in the harmonics:
   $$1 - 0.811 = 0.189$$
4. **The THD.**
   $$\begin{aligned} \text{THD} &= \sqrt{\frac{0.189}{0.811}} \\ &= \sqrt{\frac{\pi^2}{8} - 1} \\ &= 0.483 \end{aligned}$$
5. **What it means.** A function generator's square output is 48% distortion by this measure, which is why "THD" is only meaningful for something meant to be a sine.

**Answer:** the THD is 0.483, or 48%.
:::
:::

::: check
given: f = 1 | 2 | 5
answer: (1/3)*sqrt((1 + 1/f^2)/(1 + 9/f^2))
tolerance: 0.5%

## A ±1 square wave at 1 kHz passes through an RC low-pass with its corner at {f} kHz. What is the ratio of the output's 3rd harmonic to its fundamental?

::: right
Right. $\frac13 \cdot \frac{|H(3)|}{|H(1)|}$ = {answer}.
:::

::: misses
- [1/3] That's the input's ratio; the filter cuts the 3rd harmonic more.
- [any] Not yet. $|H(f)| = \frac{1}{\sqrt{1 + (f/f_c)^2}}$.
:::
:::

::: check
given: N = 3 | 5 | 9
answer: sqrt(1 - 8/pi^2*(1 + step(N - 2)/9 + step(N - 4)/25 + step(N - 6)/49 + step(N - 8)/81))
tolerance: 0.5%

## A ±1 square wave is rebuilt from its odd harmonics up to and including {N}. What RMS error remains?

::: right
Right. By Parseval, the missing harmonics' power is $1 - \sum\frac{8}{\pi^2n^2}$; its square root is {answer}.
:::

::: misses
- [any] Not yet. Subtract the included harmonics' power from the total mean square, 1.
:::
:::

::: check
kind: python

## For a ±1 square wave of period 1, sampled at 200 001 points, compute $b_1$, $b_2$ and $b_3$ by the trapezoid rule and set `b`. (The wave is `np.sign(np.sin(2 * np.pi * t))`.)

```python starter
import numpy as np

t = np.linspace(0, 1, 200001)
x = np.sign(np.sin(2 * np.pi * t))
b = [0, 0, 0]
print(b)
```

```python solution
import numpy as np

t = np.linspace(0, 1, 200001)
x = np.sign(np.sin(2 * np.pi * t))
b = [2 * np.trapezoid(x * np.sin(2 * np.pi * n * t), t) for n in (1, 2, 3)]
print(b)
```

```python tests
import math
import numpy as np
assert np.allclose(b, [4 / math.pi, 0, 4 / (3 * math.pi)], atol=1e-6), f"The coefficients are 4/pi, 0 and 4/(3 pi); got {b}."
```

::: right
Right. $\frac4\pi$, 0 and $\frac{4}{3\pi}$: the even harmonics vanish by symmetry.
:::
:::

::: check
kind: python

## Sum the first 200 odd harmonics ($n$ up to 399) of the ±1 square wave on 40 001 points over $0 \le t \le 0.02$ and set `peak` to the largest value.

```python starter
import numpy as np

peak = 1.0
print(peak)
```

```python solution
import numpy as np

t = np.linspace(0, 0.02, 40001)
s = sum(4 / (np.pi * n) * np.sin(2 * np.pi * n * t) for n in range(1, 401, 2))
peak = s.max()
print(peak)
```

```python tests
assert 1.175 < peak < 1.182, f"The Gibbs peak approaches 1.179; got {peak}."
```

::: right
Right. About 1.179, 9% of the jump above the top, however many terms you add.
:::
:::

::: check
kind: python

## Check Parseval's theorem: set `total` to $\sum\frac{b_n^2}{2}$ over the square wave's odd harmonics up to $n$ = 20 001, which should approach the mean square, 1.

```python starter
import math

total = 0.0
print(total)
```

```python solution
import math

total = sum((4 / (math.pi * n))**2 / 2 for n in range(1, 20002, 2))
print(total)
```

```python tests
assert 0.9999 < total < 1, f"The harmonics' power should approach 1 from below; got {total}."
```

::: right
Right. Ten thousand terms account for all but 0.002% of the power: the tail of $\frac{1}{n^2}$ is small.
:::
:::

::: check
kind: python

## Write `thd(amps)` returning the total harmonic distortion of a list of harmonic amplitudes (fundamental first). Set `t_sq` for the square wave's odd harmonics up to $n$ = 9999 (with zeros for the even ones), and `exact` to $\sqrt{\pi^2/8 - 1}$.

```python starter
import math

def thd(amps):
    return 0.0

amps = [4 / (math.pi * n) if n % 2 else 0.0 for n in range(1, 10000)]
t_sq = thd(amps)
exact = 0.0
print(t_sq, exact)
```

```python solution
import math

def thd(amps):
    return math.sqrt(sum(a * a for a in amps[1:])) / amps[0]

amps = [4 / (math.pi * n) if n % 2 else 0.0 for n in range(1, 10000)]
t_sq = thd(amps)
exact = math.sqrt(math.pi**2 / 8 - 1)
print(t_sq, exact)
```

```python tests
import math
assert abs(exact - math.sqrt(math.pi**2 / 8 - 1)) < 1e-12, "exact should be sqrt(pi^2/8 - 1)."
assert abs(t_sq - exact) < 1e-3, f"The square wave's THD is 0.4834; got {t_sq}."
assert abs(thd([10, 0.2, 0.1]) - math.sqrt(0.05) / 10) < 1e-12, "An amplifier with 10, 0.2 and 0.1 V harmonics has THD 2.24%."
```

::: right
Right. 48.3%: a square wave is as far from a sine as a periodic signal usually gets.
:::
:::

::: check
kind: python

## Filter the square wave through an RC low-pass with its corner at the fundamental: multiply each odd harmonic $n$ (up to 999) by $\frac{1}{\sqrt{1 + n^2}}$. Set `ratio3` to the output's 3rd harmonic over its fundamental and `thd_out` to the output's THD.

```python starter
import math

ratio3 = thd_out = 0.0
print(ratio3, thd_out)
```

```python solution
import math

out = {n: 4 / (math.pi * n) / math.sqrt(1 + n * n) for n in range(1, 1000, 2)}
ratio3 = out[3] / out[1]
thd_out = math.sqrt(sum(a * a for n, a in out.items() if n > 1)) / out[1]
print(ratio3, thd_out)
```

```python tests
import math
assert abs(ratio3 - math.sqrt(0.2) / 3) < 1e-12, f"The 3rd harmonic falls to 0.149 of the fundamental; got {ratio3}."
assert 0.15 < thd_out < 0.2, f"The filtered wave's THD drops from 48% to under 20%; got {thd_out}."
```

::: right
Right. One pole takes the THD from 48% to about 17%: much rounder, still visibly not a sine.
:::
:::

::: explain
## Why doesn't the Gibbs overshoot shrink as you add more harmonics, even though the series converges?

::: model
Each added harmonic sharpens the transition, so the overshoot crowds closer to the jump and gets narrower, roughly in proportion to $\frac1N$. But its height is set by the shape of the transition, which is the same shape scaled narrower: the partial sum near the jump approaches a fixed function of $Nt$, the sine integral, whose peak is 1.179. At any fixed point away from the jump, the overshoot eventually passes by and the series converges there; it just never converges uniformly. In practice it means a perfectly sharp low-pass filter will always ring by about 9% on a step, and smoother filters trade that ringing for a slower edge.
:::
:::

::: practice

::: check
given: f = 0.5..10
answer: (1/3)*sqrt((1 + 1/f^2)/(1 + 9/f^2))
tolerance: 0.5%

## 3rd-to-fundamental ratio after an RC low-pass at {f} times the fundamental?

::: misses
- [any] $\frac13\sqrt{\frac{1 + 1/f^2}{1 + 9/f^2}}$.
:::
:::

::: check
given: a = 1..10; b = 0.01..2; c = 0.01..2
answer: sqrt(b^2 + c^2)/a
tolerance: 0.5%

## THD with harmonic amplitudes {a}, {b} and {c}?

::: misses
- [any] $\frac{\sqrt{b^2 + c^2}}{a}$.
:::
:::
:::
