Gallery · Mathematics

A square wave, one sine at a time

NumPy adds odd harmonics until a square wave appears, and the prose alongside carries the series itself in TeX, typeset in place. A zoom on the jump finds the Gibbs overshoot refusing to shrink, and Parseval closes the books.

fourier-series.verso Python · 6 cells Read-only preview Download

A square wave, one sine at a time

The square wave is the classic stress test for a Fourier series: a function that is all corners, rebuilt from the smoothest ingredients mathematics has. Only the odd harmonics take part, each weighted down by its own frequency:

$$ f(t) = \frac{4}{\pi} \sum_{k \text{ odd}} \frac{\sin(kt)}{k} $$

Cut the sum off after $N$ harmonics and you get a trigonometric polynomial $S_N(t)$ that leans toward the wave without ever being it. The figures below are baked from a real run: the code computed them, the page just remembers.

[1]
codePython
1import numpy as np
2import matplotlib.pyplot as plt
3
4t = np.linspace(-np.pi, np.pi, 4000)
5square = np.sign(np.sin(t))
6
7def partial_sum(t, n_terms):
8 # The first n_terms odd harmonics: k = 1, 3, 5, ...
9 k = np.arange(1, 2 * n_terms, 2)
10 return (4 / np.pi) * np.sin(np.outer(t, k)) @ (1 / k)
11
12fig, ax = plt.subplots(figsize=(7.5, 4.2))
13ax.plot(t, square, color="0.3", linewidth=1.2, label="square wave")
14for n, color in [(1, "#c7d2fe"), (3, "#93c5fd"), (9, "#3b82f6"), (41, "#1e40af")]:
15 label = f"{n} term" + ("s" if n > 1 else "")
16 ax.plot(t, partial_sum(t, n), linewidth=1.0, color=color, label=label)
17ax.set_xlim(-np.pi, np.pi)
18ax.set_ylim(-1.45, 1.45)
19ax.set_title("Partial sums closing in on the square wave")
20ax.legend(loc="lower right", fontsize=8, framealpha=0.9)
21plt.tight_layout()
22plt.show()
✓completed

The overshoot that never leaves

Watch the corners. Near each jump the partial sums spike past the target, and adding harmonics makes the spike thinner without making it shorter. Its height converges to a constant of its own,

$$ \lim_{N \to \infty} \max_t S_N(t) = \frac{2}{\pi} \int_0^{\pi} \frac{\sin u}{u} \, du \approx 1.1790, $$

which lands about $9\%$ of the jump too far. This is the Gibbs phenomenon: the series converges in $L^2$, and the corners never stop objecting.

[2]
codePython
1# The Gibbs limit, integrated the plain way: a midpoint sum of sin(u)/u over (0, pi).
2u = (np.arange(200000) + 0.5) * (np.pi / 200000)
3gibbs = (2 / np.pi) * np.sum(np.sin(u) / u) * (np.pi / 200000)
4
5window = np.linspace(0, 0.25, 20000)
6fig, ax = plt.subplots(figsize=(7.5, 4.2))
7for n, color in [(21, "#93c5fd"), (101, "#3b82f6"), (501, "#1e40af")]:
8 s = partial_sum(window, n)
9 ax.plot(window, s, linewidth=1.0, color=color,
10 label=f"{n} terms, peak {s.max():.4f}")
11ax.axhline(1.0, color="0.6", linewidth=0.8)
12ax.axhline(gibbs, color="0.3", linewidth=0.8, linestyle="--",
13 label=f"Gibbs limit {gibbs:.4f}")
14ax.set_xlim(0, 0.25)
15ax.set_ylim(0.8, 1.25)
16ax.set_title("Zoom on the jump at t = 0: thinner, never shorter")
17ax.legend(loc="lower right", fontsize=8, framealpha=0.9)
18plt.tight_layout()
19plt.show()
✓completed

Parseval closes the books

Squaring the wave and squaring its coefficients count the same energy, and for the square wave that bookkeeping becomes an identity about plain numbers:

$$ \frac{8}{\pi^2} \sum_{k \text{ odd}} \frac{1}{k^2} = 1, $$

so the odd reciprocal squares alone sum to $\pi^2 / 8$. The cell below watches the running total arrive.

[3]
codePython
1k = np.arange(1, 100000, 2)
2running = (8 / np.pi**2) * np.cumsum(1.0 / k**2)
3for n in [1, 2, 5, 10, 100, 1000, 50000]:
4 print(f"{n:>6} odd harmonics: {running[n - 1]:.8f}")
✓completed
     1 odd harmonics: 0.81056947
     2 odd harmonics: 0.90063274
     5 odd harmonics: 0.95960479
    10 odd harmonics: 0.97975259
   100 odd harmonics: 0.99797359
  1000 odd harmonics: 0.99979736
 50000 odd harmonics: 0.99999595

Run it yourself

Nothing on this page is executable; the outputs were baked in by a real run. Download the notebook and it runs anywhere Verso does: VS Code, the browser, or the terminal.

dotnet tool install --global Verso.Cli
verso serve fourier-series.verso

What this shows

NumPy adds odd harmonics until a square wave appears, and the prose alongside carries the series itself in TeX, typeset in place. A zoom on the jump finds the Gibbs overshoot refusing to shrink, and Parseval closes the books.

Every language in this notebook reads and writes the same variable store, so a value produced in one cell is simply there in the next, whatever the language.