Interactive deep dive · Signal processing
The Fast Fourier Transform: hearing what the eye cannot see
How to go from \(4n^2\) to \(n\log n\) multiplications — and why this 1965 trick, already known to Gauss, runs your phone, MRI scanners and the spectral analysis of any time series.
Decomposes a sampled signal into frequency components.
Computes the same transform using divide and conquer, much faster.
Detect rhythms, filter noise and decode real audio signals.
Why this matters
A temperature sensor records one value per minute, a microphone 44,100 per second, your phone's accelerometer about a hundred. In all these cases the useful question is rarely "what was the value at 2:03 pm?". It is rather: which rhythms make up this signal? The 24-hour cycle, the 440 Hz note, the vibration of a bearing that is starting to wear out.
The discrete Fourier transform (DFT) answers exactly that question. But computed naively it costs \(N^2\) complex multiplications for \(N\) samples: for a single second of audio, almost two billion. The Cooley–Tukey algorithm (1965) brings this down to the order of \(N\log_2 N\) — under a million for the same second. This is not a marginal optimisation: it is the difference between a blackboard idea and MP3/JPEG compression, 4G/5G (OFDM), MRI image reconstruction, fast convolution and the spectral analysis of every time series.
The route: we start from the trigonometric interpolating polynomial, prove discrete orthogonality, build the Fourier matrix, then break it in two — recursively. Then we move on to signal processing: spectral leakage, aliasing, filtering, and a real phone-keypad decoder running in your browser. Every numerical example has been recomputed and checked.
The problem: three notes in the noise
Here is a signal sampled 256 times over 5 seconds. It contains exactly three sinusoids plus Gaussian noise. Before you click "Reveal", try to say how many frequencies you see, and which ones.
The signal is \(f(x) = 15\cos(20x)\) \(+\,5\sin(30x)\) \(-\,10\cos(42x)\), with noise added; we will meet it again later, without noise. In the time domain the three components tangle together: their interference produces beats that look like a random envelope. In the frequency domain they separate into three sharp peaks — even when the noise standard deviation (6) exceeds the smallest amplitude (5).
Polynomials that rotate
To approximate a periodic function, classical polynomials (Lagrange, Newton, splines) are a poor fit: they do not repeat. We use polynomials that are periodic themselves. First map \([a,b]\) to \([0,2\pi]\) with \(t = 2\pi\,\frac{x-a}{b-a}\).
So we need \(2n\) interpolation points. Since \(g(2\pi)=g(0)\), take \(t_k = k\pi/n\), \(k=0,\dots,2n-1\), and impose \(T_n(t_k)=g(t_k)\).
Example: the parabola. For \(f(x)=x(1-x)\) on \([0,1]\) with 4 points, the sampled values are \([0,\tfrac{3}{16},\tfrac14,\tfrac{3}{16}]\). Solving the \(4\times4\) system gives \([a_0,a_2,a_1,b_1] = [\tfrac{5}{16},-\tfrac1{16},-\tfrac18,0]\), hence
\[ T_2(t) = \frac{5-\cos 2t}{32} - \frac18\cos t. \]It works, but it is the trigonometric analogue of the Vandermonde matrix: solving a dense system costs \(O(n^3)\). We can do much better, because the columns of this system are orthogonal.
Discrete orthogonality
On the points \(t_k\), define the inner product \((f,g)_d = \sum_{k=0}^{2n-1} f(t_k)\,\overline{g(t_k)}\).
The proof fits in one line: it is a geometric series with ratio \(r=e^{i\pi(m-l)/n}\), and \(r^{2n}=e^{2i\pi(m-l)}=1\), so \(\sum r^k = \frac{1-r^{2n}}{1-r} = 0\) whenever \(r\neq 1\). Geometrically: the \(2n\) vectors \(r^k\) are evenly spread on the circle, and placed head to tail they close a polygon.
Try \(m-l=0\), then \(m-l=2n\): every vector equals 1 and the sum is \(2n\) — one special case of the lemma (likewise \(m=-n,\,l=n\)). For any other value the polygon closes (sometimes after several turns).
Orthogonality turns the linear system into simple projections. Multiply \(T_n(t_k)=g(t_k)\) by \(e^{-ilt_k}\), sum over \(k\), and every term vanishes but one:
On the parabola there is no longer a system to solve: \(a_0 = \tfrac12(0+\tfrac3{16}+\tfrac14+\tfrac3{16}) = \tfrac5{16}\), and likewise \(a_1=-\tfrac18\), \(a_2=-\tfrac1{16}\), \(b_1=0\). Cost: \(2n\) multiplications per coefficient, so \(4n^2 = N^2\) in total. Better than \(O(n^3)\), but for a million samples that is still \(10^{12}\).
Quick check · If 2n = 8 and m − l = 8, does the sum vanish?
No. Every term equals 1 because \(e^{2\pi ik}=1\), so the sum is 8. Orthogonality applies when \(m-l\not\equiv0\pmod 8\).
The Fourier matrix
Introduce the complex coefficients \(c_l = \sum_{k} g(t_k)\,w^{lk}\) with \(w=e^{i\pi/n}\). Expanding \(w^{lk} = \cos(lt_k) + i\sin(lt_k)\) shows that \(\frac1n c_l = a_l + i\,b_l\): the whole polynomial is recovered from the vector \(\vec c\). In matrix form, \(\vec c = F\,\vec g\) with \(F_{lk} = w^{lk}\), and \(F^{-1} = \frac{1}{2n}\overline{F}\) — the matrix is unitary up to a factor.
Look at it: each cell is coloured by the phase of \(w^{lk}\). Then tick "reorder": the even columns go to the left, the odd ones to the right.
After reordering, the matrix splits into four blocks, and the simulator checks two identities numerically: the top-left block is identical to the bottom-left block, and the top-right block is the negative of the bottom-right block. More precisely, if \(P\) is the even/odd permutation and \(D=\mathrm{diag}(1,w,\dots,w^{n-1})\):
\[ F_{2n}\,P = \begin{pmatrix} F_n & D\,F_n \\ F_n & -D\,F_n \end{pmatrix}, \]where \(F_n\) is the Fourier matrix of size \(n\) (built with \(w^2\)). The whole FFT is in this picture: a DFT of size \(2n\) = two DFTs of size \(n\), plus \(n\) multiplications by the \(w^l\).
Cooley–Tukey: divide and conquer
Algebraically, split the sum by the parity of \(k\). For \(l=0,\dots,n-1\), with \(E_l = \sum_{k=0}^{n-1} g(t_{2k})\,e^{2ilk\pi/n}\) (even samples) and \(O_l = \sum_{k=0}^{n-1} g(t_{2k+1})\,e^{2ilk\pi/n}\) (odd samples):
\[ c_l = E_l + w^l\,O_l,\qquad c_{n+l} = E_l - w^l\,O_l. \]These two lines form a "butterfly": two inputs, one multiplication by \(w^l\) (the twiddle factor), one addition, one subtraction. And \(E\), \(O\) are themselves DFTs of size \(n\): repeat until the DFTs have size 1, which cost nothing. The recursive algorithm fits in about ten lines (see the first Python cell).
On the parabola (\(N=4\)), follow the full computation: the signal \([0,\tfrac3{16},\tfrac14,\tfrac3{16}]\) is first split into \([0]\,[\tfrac14]\,[\tfrac3{16}]\,[\tfrac3{16}]\) (bit-reversed order: index 1 = 01₂ moves to position 10₂ = 2), then recombined into \([\tfrac14,-\tfrac14]\) and \([\tfrac38,0]\), then into \(\vec c = [\tfrac58,-\tfrac14,-\tfrac18,-\tfrac14]\). At the last step the simulator checks the result against the direct product with the Fourier matrix and prints \(a_0=\tfrac5{16}\), \(a_1=-\tfrac18\), \(b_1=0\), \(a_2=-\tfrac1{16}\). On the symmetric bump \([0,7,12,15,16,15,12,7]/64\) (\(N=8\)) we get \(c_0=\tfrac{21}{16}\), \(c_1=-\tfrac14-\tfrac{\sqrt2}{8}\approx-0.4268\), and so on.
Try the impulse \(\delta\) as well: its spectrum is flat (all frequencies equal) — and the pure cosine, whose spectrum has only two non-zero coefficients, \(c_1\) and \(c_7=c_{-1}\).
Counting operations
If \(M(N)\) is the number of multiplications for a DFT of size \(N=2^p\), the butterfly gives \(M(N) = 2M(N/2) + N/2\), hence
\[ M(N) = \frac{N}{2}\log_2 N. \]For a general size \(N = 2^p q\) with \(q>1\) odd, this recursive strategy uses \(2^p q^2 + \tfrac{pN}{2}\) complex multiplications if each odd-size \(q\)-point DFT is computed directly (without exploiting trivial twiddle factors). The first term accounts for the \(2^p\) leaf transforms; the second is the cost of the butterfly stages. When \(q=1\), the size-1 leaves require no multiplications. Better FFT algorithms also handle odd factors efficiently.
History: Gauss found the idea around 1805 while interpolating the orbits of the asteroids Pallas and Juno, in a manuscript published posthumously (Heideman, Johnson and Burrus, 1984). Cooley and Tukey rediscovered it in 1965, just as computers made it indispensable.
Try it · For N = 1024, why are there only 10 butterfly stages?
Each stage doubles the transform size: 1 → 2 → 4 → … → 1024. Since \(1024=2^{10}\), there are \(\log_2(1024)=10\) stages, each with \(N/2=512\) butterflies.
How much do we gain?
On a log scale the direct DFT is a line of slope 2; the FFT is a line of slope barely above 1. The measure button times both algorithms in JavaScript on your machine, from \(N=64\) to \(N=4096\): the measured gain follows the theoretical gain, up to a constant.
Amplitude, phase, frequency
Each term of the polynomial can be written \(S_j(t) = a_j\cos jt + b_j\sin jt\) \(= A_j\cos(jt-\delta_j)\), with
\[ A_j = \sqrt{a_j^2+b_j^2} = \frac{|c_j|}{n},\qquad \delta_j = \operatorname{atan2}(b_j,a_j),\qquad f_j = \frac{j}{b-a},\quad 1\le j < n. \]Plotting \(A_j\) against \(f_j\) gives the spectrum of the signal. Two settings matter: the duration \(T=b-a\) sets the resolution \(\Delta f = 1/T\), and the number of samples sets the maximum frequency \(f_{\max} = n/T = f_s/2\).
At DC (\(j=0\)) and the Nyquist bin (\(j=n\)), use half that scaling: \(A_0=|c_0|/(2n)\) and \(A_n=|c_n|/(2n)\), with the phase interpreted separately.
Pure cosine. \(f(x)=15\cos 3\pi x\) sampled at \(2n=2^9\) points on \([0,10]\): the frequency is \(3\pi/2\pi = 1.5\) Hz, there are exactly 15 cycles in the window, and the FFT returns amplitude 15 and frequency 1.5 exactly.
Three components. Back to the opening signal, without noise: with \(2n = 2^8\) points over 5 s, the FFT finds peaks at 3.2, 4.8 and 6.6 Hz with amplitudes 14.74, 5.18 and 7.38. But why not 15, 5 and 10? Because \(\frac{20}{2\pi}\times 5 = 15.92\) cycles: the sinusoid does not "land" on the grid \(f_j = j/5\). Its energy leaks into neighbouring frequencies (spectral leakage) and the peak is both shifted (3.2 instead of 3.183) and flattened. The component at \(42/2\pi\) Hz, 0.42 of a bin away from the grid, loses more than a quarter of its amplitude. With a Hann window (below) the three amplitudes become 14.93, 4.95 and 8.90: much closer to the truth.
Aliasing
With \(2n\) points over a duration \(T\), the representable frequencies stop at \(f_j = n/T = f_s/2\): the Nyquist frequency. What happens to a faster sinusoid? It does not vanish: it disguises itself. Once sampled, \(\sin(2\pi f_0 t)\) is indistinguishable from \(\pm\sin(2\pi f_a t)\), where \(f_a\) is the distance from \(f_0\) to the nearest multiple of \(f_s\).
The white dots are the samples; the dashed amber curve is the slowest sinusoid passing exactly through those same points. With \(f_0=7\) Hz and \(f_s=10\) Hz, the samples "see" 3 Hz. This is the stroboscopic effect that makes stagecoach wheels appear to spin backwards in films. Practical consequence: you must filter before sampling (anti-aliasing filter), because once the points are taken the information is gone. CDs sample at 44.1 kHz to cover human hearing up to about 20 kHz.
Predict it · What does an 18 Hz sine wave look like when sampled at 10 Hz?
It aliases to 2 Hz: \(18 = 2\times10-2\). For a sine wave, the sampled 18 Hz signal has a negative sign relative to \(\sin(2\pi\,2t)\).
Filtering and convolution
Since the DFT is invertible (\(F^{-1}=\tfrac1{2n}\overline F\)), we can modify the spectrum and go back to the signal. To denoise, keep the low frequencies and zero out the rest: a low-pass filter. The scenario below mimics a week of hourly sensor readings — a 24 h cycle, its first harmonic (12 h) and a slow drift.
The smooth signal only has energy at indices 1, 7 and 14 (cycles per week): a cutoff at \(j_c = 16\) keeps only \(33/512\approx 6\,\%\) of the coefficients, and so removes about 94 % of the noise variance. On the square wave, a brick-wall cutoff produces oscillations near the jumps that never fully disappear: the Gibbs phenomenon, with an overshoot of about 9 % of the jump. The gentler Gaussian filter attenuates them at the cost of softer edges.
The convolution theorem
Multiplying two spectra term by term amounts to convolving the signals (circularly): \(\widehat{g*h} = \hat g\cdot\hat h\). A direct convolution costs \(O(N^2)\); via the FFT, \(O(N\log N)\). This is how high-degree polynomials and integers with millions of digits are multiplied (Schönhage–Strassen, then Harvey–van der Hoeven, who reached \(O(n\log n)\) in 2019), and how long filters are applied in audio. The third Python cell below multiplies two 20,000-digit integers by FFT and checks the result.
Application: decoding a phone keypad
Each key of a telephone emits the sum of two sinusoids (ITU-T Recommendation Q.23, "DTMF"): a row frequency among 697, 770, 852 and 941 Hz, and a column frequency among 1209, 1336, 1477 and 1633 Hz. These values were chosen so that none is a simple harmonic of another, so that the human voice rarely triggers a false key. The exchange receives 8000 samples per second; with \(N = 256\) (32 ms), the resolution is \(\Delta f = 8000/256 = 31.25\) Hz, fine enough to separate 697 from 770 Hz.
For the sequence we compute a spectrogram: successive FFTs over windows of 256 samples shifted by 64. Each key leaves two horizontal strokes. The decoder reads each window, looks for the dominant peak in each group and requires it to clearly dominate both the noise and the second peak of its group. Turn up the noise: around \(\sigma\approx 1\) — a signal-to-noise ratio of about −6 dB per sample — keys start being missed, then misread. In practice, exchanges often use the Goertzel algorithm, which computes only the 8 useful coefficients — cheaper than a full FFT when so few frequencies are needed.
In practice (Python)
These cells run in your browser (Pyodide). The first one writes out the recursive algorithm described above and compares it with numpy.
Limits and pitfalls
- Normalisation. Here we divide by \(n\) to get \(a_l + ib_l\); NumPy does not divide on the way forward and divides by \(N\) on the way back; other conventions divide by \(\sqrt N\) both ways. Always check on a known example, such as \(15\cos 3\pi x\).
- Implicit periodicity. The DFT treats the window as one period. Any discontinuity between the last and the first sample creates leakage: remove the trend, then window.
- Resolution ≠ sampling. \(\Delta f = 1/T\) depends only on the duration. Zero-padding nicely interpolates the spectrum, but it does not separate two frequencies closer than \(1/T\).
- Aliasing is irreversible. A frequency beyond \(f_s/2\) folds back and becomes indistinguishable from a genuine low frequency. Filter before sampling, never after.
- Arbitrary sizes. Radix-2 FFT wants \(N=2^p\). The recursive version in this article handles \(N=2^pq\); modern libraries (FFTW, pocketfft) handle all factors, even prime sizes (Rader's and Bluestein's algorithms).
- Non-stationary signals. A single spectrum averages over the whole duration. If the frequencies change (speech, chirps, a DTMF sequence), you need a spectrogram or wavelets.
- Accuracy. In floating point, the FFT's rounding-error bound grows like \(\log N\), against \(N\) for the direct sum (worst-case bounds): the fast algorithm is also the more accurate one.
References
- A. Fortin. Approximation des fonctions et résolution numérique des EDO, EDS et EDP. Course text, Université Laval (trigonometric interpolation and the FFT).
- J. W. Cooley and J. W. Tukey (1965). An algorithm for the machine calculation of complex Fourier series. Mathematics of Computation, 19(90), 297–301.
- M. T. Heideman, D. H. Johnson and C. S. Burrus (1984). Gauss and the history of the fast Fourier transform. IEEE ASSP Magazine, 1(4), 14–21.
- F. J. Harris (1978). On the use of windows for harmonic analysis with the discrete Fourier transform. Proceedings of the IEEE, 66(1), 51–83.
- A. V. Oppenheim and R. W. Schafer (2010). Discrete-Time Signal Processing, 3rd ed. Pearson.
- C. E. Shannon (1949). Communication in the presence of noise. Proceedings of the IRE, 37(1), 10–21.
- G. Goertzel (1958). An algorithm for the evaluation of finite trigonometric series. American Mathematical Monthly, 65(1), 34–35.
- ITU-T, Recommendation Q.23 — Technical features of push-button telephone sets.
- M. Frigo and S. G. Johnson (2005). The design and implementation of FFTW3. Proceedings of the IEEE, 93(2), 216–231.
- D. Harvey and J. van der Hoeven (2021). Integer multiplication in time O(n log n). Annals of Mathematics, 193(2), 563–617.