CodeRigor

LESSON

The fast Fourier transform

Split a transform into halves, combine them with butterflies in log n stages, and use the result to convolve long signals and count the saved work.

The direct transform from the lesson before this one multiplies a signal by an n × n matrix, which costs n² complex multiplications. At 65,536 samples, about 1.5 seconds of CD audio, that is 4,294,967,296 of them. The fast Fourier transform produces the same numbers with 524,288. This lesson pairs with The Fast Fourier Transform (FFT): Most Ingenious Algorithm Ever? by Reducible, linked under Watch & read. The video reaches the algorithm through polynomial multiplication and roots of unity; here you build an iterative radix-2 version in NumPy, use it to convolve long signals, and count the work it saves.

The idea is to split the signal. Write w = e^(-2πi/n) and let E and O be the transforms of the even-numbered and the odd-numbered samples, each of length m = n/2. For k from 0 to m - 1:

  • X[k] = E[k] + wᵏ · O[k]
  • X[k + m] = E[k] - wᵏ · O[k]

The second line holds because E and O repeat with period m, while w^(k+m) = -wᵏ. One multiplication by the twiddle factor wᵏ therefore feeds two outputs. That pair of lines is called a butterfly, and a transform of length n needs n/2 of them on top of the two half-size transforms. Apply the split again to each half, and again, until a block holds one sample, whose transform is the sample itself.

Run the recursion backwards and it becomes a loop. First reorder the samples so that each block the recursion would reach is already contiguous: sample i moves to the position whose bits are those of i in reverse order. Then do log₂ n stages. In the stage with block size s, every block of s values combines its two halves with the twiddles e^(-2πik/s) for k from 0 to s/2 - 1. The factor depends on the block size of that stage, not on the full length n; only the last stage has s = n.

Bit reversal, then three stages of merging
start / 4
Eight samples after bit-reversed reordering. Stage 1 merges neighbours into blocks of 2, stage 2 into blocks of 4, stage 3 into one block of 8.
Bit reversal, then three stages of merging
Eight samples after bit-reversed reordering. Stage 1 merges neighbours into blocks of 2, stage 2 into blocks of 4, stage 3 into one block of 8.

Take x = [1, 2, 3, 4]. The even samples [1, 3] transform to E = [4, -2]; the odd samples [2, 4] transform to O = [6, -2]. The twiddles for k = 0 and 1 are 1 and -i. The butterflies give X[0] = 4 + 6 = 10, X[1] = -2 + (-i)(-2) = -2 + 2i, X[2] = 4 - 6 = -2 and X[3] = -2 - 2i. The snippet repeats this with NumPy's own transform for the halves.

Python
import numpy as np

x = np.array([1.0, 2.0, 3.0, 4.0])
even, odd = np.fft.fft(x[0::2]), np.fft.fft(x[1::2])
w = np.exp(-2j * np.pi * np.arange(2) / 4)
X = np.concatenate([even + w * odd, even - w * odd])
print(X.real.round(6).tolist(), (X.imag + 0.0).round(6).tolist())
print(np.allclose(X, np.fft.fft(x)))

Counting the work is easy because every stage has n/2 butterflies and there are log₂ n stages, so the FFT needs (n/2) log₂ n multiplications against n² for the direct sum. For n = 8 that is 12 against 64. For n = 1,024 it is 5,120 against 1,048,576, a factor of 204.8. The gap widens with n, since n² grows faster than n log n. The count here includes the multiplications by 1 at k = 0, so it counts butterflies, not nontrivial products.

Python
for k in (3, 10, 16):
    n = 2 ** k
    print(n, n * n, n // 2 * k, round(n * n / (n // 2 * k), 1))
Complex multiplications, direct DFT against FFT
Both axes are logarithmic and n doubles at every point, from 2 to 65,536. The direct sum is a steeper line; the FFT stays far below it.
Complex multiplications, direct DFT against FFT
Both axes are logarithmic and n doubles at every point, from 2 to 65,536. The direct sum is a steeper line; the FFT stays far below it.

Three more tools fall out of the same loop. The inverse transform is the identical loop with e^(+2πik/s) as the twiddle, followed by a division by n. Two real signals can share one transform: put x in the real part and y in the imaginary part of z = x + iy, transform once, and separate them with X[k] = (Z[k] + conj(Z[n - k])) / 2 and Y[k] = (Z[k] - conj(Z[n - k])) / 2i, where n - k is taken modulo n. This works because the spectrum of a real signal is conjugate symmetric.

Convolution is the third. Multiplying two spectra gives the circular convolution of the signals, whose length is the transform length. The linear convolution of lengths p and q has p + q - 1 entries, so both signals must be padded with zeros to at least that length, rounded up to a power of two. With less padding the tail wraps around onto the start.

Python
import numpy as np

a, b = np.array([1.0, 2.0, 3.0]), np.array([4.0, 5.0])
for size in (3, 4):
    prod = np.fft.fft(a, size) * np.fft.fft(b, size)
    print(size, np.fft.ifft(prod).real.round(6).tolist())

With size 3 the fourth product, 15, wraps onto the first entry and 4 becomes 19. With size 4 the answer is the true [4, 13, 22, 15].

These are the mistakes to expect. Padding to the longer input, or to the next power of two above it, passes some tests and fails others, depending on whether the wrapped tail is nonzero. Using the full length n in every stage's twiddle, instead of the block size of that stage, is correct for lengths 2 and 4 and wrong from 8 on, so a test at length 4 will not find it. A length that is not a power of two cannot be halved all the way down to single samples, so reject it with a ValueError before any work.

The tests compare your transform with NumPy's at several lengths, check that the inverse undoes it, compare convolutions with np.convolve, and check one length-4 case by hand. Agreement is to about 1e-9, not exactly, because the two programs round differently. These checks do not measure speed: the Python loop over blocks is slower than NumPy's compiled code, and operation_count is a formula, not a timing.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →