The Fast Fourier Transform
Multiplying polynomials in O(n log n) with roots of unity.
Multiplying two polynomials of degree coefficient by coefficient takes operations. The fast Fourier transform does it in by a detour: evaluate both polynomials at the complex roots of unity, multiply the values, and interpolate back. Gauss knew the trick around 1805; Cooley and Tukey's rediscovery in 1965 made it one of the most used algorithms ever written.
What you’ll learn
- Express polynomial multiplication as a convolution, and explain why the point-value representation makes multiplication cheap.
- Derive the radix-2 FFT from the halving lemma for roots of unity, and the inverse transform from the DFT matrix.
- Implement the FFT recursively and in place with the bit-reversal permutation, and judge its floating-point error.
- Use the number-theoretic transform modulo for exact integer convolution.
- Apply convolution to big-integer multiplication, wildcard string matching and counting pair sums.
Multiplying polynomials is convolution
Let and . Their product has coefficients
the convolution of the two coefficient sequences. Computed directly, that is multiplications.
A polynomial of degree less than is also determined by its values at any distinct points (the Vandermonde matrix of the points is invertible). In this point-value form, multiplication is pointwise: , only work, provided both polynomials are evaluated at the same points.
| Stage | Operation | Cost |
|---|---|---|
| Evaluate | and at chosen points | by Horner at arbitrary points; at roots of unity |
| Multiply | ||
| Interpolate | recover the coefficients of | in general; at roots of unity |
Roots of unity and the halving lemma
Let , a principal -th root of unity; its powers are the points with . The discrete Fourier transform of is the vector of values . Take a power of 2, padding with zero coefficients.
Split by even and odd coefficients:
Halving lemma. For even , squaring the -th roots of unity gives the -th roots of unity, each twice, and opposite roots differ by a sign:
So with and the DFTs of length of the even and odd coefficients, the values come from the butterfly:
Two half-size transforms and butterflies:
The DFT is multiplication by the Vandermonde matrix . For (mod ), is a root of , so the geometric sum vanishes:
Hence the matrix with entries , times , is times the identity, and the inverse DFT is the same transform with , divided by :
import cmath
def fft(a, invert=False): # len(a) must be a power of 2
n = len(a)
if n == 1:
return a[:]
even = fft(a[0::2], invert) # A_even at the (n/2)-th roots of unity
odd = fft(a[1::2], invert) # A_odd at the same points
sign = -1 if invert else 1
out = [0] * n
for k in range(n // 2):
w = cmath.exp(sign * 2j * cmath.pi * k / n) # omega_n^k (or its inverse)
out[k] = even[k] + w * odd[k] # the butterfly
out[k + n // 2] = even[k] - w * odd[k]
return out
def multiply(p, q): # integer coefficients, lowest degree first
n = 1
while n < len(p) + len(q) - 1:
n *= 2
fp = fft(p + [0] * (n - len(p)))
fq = fft(q + [0] * (n - len(q)))
prod = fft([x * y for x, y in zip(fp, fq)], invert=True)
return [round((c / n).real) for c in prod[:len(p) + len(q) - 1]]multiply([1, 2, 3], [4, 5]) returns [4, 13, 22, 15]: . The transform length is the smallest power of 2 that holds all the product's coefficients.
In place, in floating point, and modulo a prime
Unroll the recursion and the leaves receive the coefficients in bit-reversed order: for , the order is , because index lands in position , and so on. Production FFTs permute the array into that order once, then run rounds of butterflies in place: no recursion, no extra arrays, good locality. Libraries such as FFTW go further and time many decompositions to keep the fastest one for the given and machine.
ITERATIVE-FFT(a): # n = len(a), a power of 2
permute a into bit-reversed index order
for len = 2, 4, 8, ..., n: # log2 n rounds
w_len ← e^(2πi / len)
for start = 0, len, 2·len, ..., n − len:
w ← 1
for k = 0, 1, ..., len/2 − 1: # butterflies, in place
u ← a[start + k]
v ← w · a[start + k + len/2]
a[start + k] ← u + v
a[start + k + len/2] ← u − v
w ← w · w_lenPrecision. Complex doubles carry 53-bit mantissas, and the rounding error grows with and with the size of the coefficients. Rounding the inverse transform to the nearest integer is safe only while the error stays below . In our test of the iterative version on 1,024 random coefficients per polynomial (with twiddle factors updated by repeated multiplication, as above), coefficients up to gave errors below , coefficients up to an error of about 0.75, enough to round wrongly, and coefficients up to errors of about 68. The remedies: split each coefficient into 15- or 16-bit halves and use more transforms, or compute exactly modulo primes.
The number-theoretic transform (NTT) replaces by the integers modulo a prime . If divides and is a primitive root modulo , then has order exactly , so , the halving lemma holds verbatim, and every operation is exact. The favorite prime of competitive programmers is , with primitive root 3.
MOD = 998244353 # 119 * 2^23 + 1, prime; 3 is a primitive root
def ntt(a, invert=False): # len(a) a power of 2, at most 2^23
n = len(a)
if n == 1:
return a[:]
even, odd = ntt(a[0::2], invert), ntt(a[1::2], invert)
w_n = pow(3, (MOD - 1) // n, MOD) # an element of order exactly n
if invert:
w_n = pow(w_n, MOD - 2, MOD) # its inverse, by Fermat's little theorem
out, w = [0] * n, 1
for k in range(n // 2):
t = w * odd[k] % MOD
out[k] = (even[k] + t) % MOD
out[k + n // 2] = (even[k] - t) % MOD
w = w * w_n % MOD
return outMultiply exactly as with fft, then scale the inverse transform by instead of dividing by . The results are the true coefficients modulo : exact when the true values are below ; larger values can be recovered from transforms modulo two or three such primes with the Chinese remainder theorem.
Modulo , transforms of length need an element of order . What is the largest such ?
Show the answer
23
An element of order exists exactly when divides . The largest power of 2 dividing it is , enough for products with about 8 million coefficients.
Applications, history and limits
Wherever a problem hides a sum of the form , convolution and the FFT apply:
- Big integers. Write the digits as coefficients, multiply the polynomials, then propagate carries. Schönhage and Strassen refined this into bit operations (see Fast Multiplication: Karatsuba to Strassen).
- All pairwise sums. For integers in , square : the coefficient of counts the ordered pairs with , for every at once, in time however large is.
- Matching with wildcards (Clifford & Clifford, 2007). Encode letters as positive integers and the wildcard as 0. Position of the text matches the pattern iff ; expanding the square gives three convolutions, so all positions are tested in .
- Signal processing. Filtering, spectral analysis and fast correlation; JPEG and MP3 rely on close relatives of the DFT, cosine transforms.
Why does detect a match at position , with wildcards encoded as 0?
- Each term is non-negative, and it is zero exactly when one of the two characters is a wildcard or the two are equal, so the sum vanishes iff every position matches
- The terms cancel in pairs whenever the strings match
- It counts the mismatches, and a count of 0 means a match, but wildcards are not handled
- It equals the edit distance between the pattern and the window
Show the answer
A. Each term is non-negative, and it is zero exactly when one of the two characters is a wildcard or the two are equal, so the sum vanishes iff every position matches
With non-negative codes, and the square is , so no cancellation is possible: the sum is 0 iff every term is 0, that is, iff at each position one character is a wildcard (a factor 0) or the characters are equal (the square is 0).
Key takeaways
- Polynomial multiplication is convolution, ; in point-value form it is pointwise, so evaluate, multiply and interpolate.
- At the -th roots of unity, and the halving lemma give ; the inverse is the same transform with , divided by .
- The in-place FFT permutes into bit-reversed order and then runs rounds of butterflies; double precision limits the size of exact integer results, and the NTT modulo (root 3) is exact.
- Convolution gives big-integer multiplication, all pairwise sums of small integers, and wildcard string matching in ; whether the DFT itself needs operations is open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why can a DFT of length be computed from two DFTs of length ?
- Because half of the -th roots of unity are real
- Because , and the squares of the -th roots of unity are just the different -th roots of unity
- Because a polynomial of degree has only independent coefficients
- Because the DFT matrix is symmetric
Show the answer
B. Because , and the squares of the -th roots of unity are just the different -th roots of unity
and are evaluated at the squares of the evaluation points, and squaring maps the roots onto only points. So each half-size polynomial needs only a half-size DFT, and the butterfly combines them.
How is the inverse DFT computed with the FFT?
- Apply the forward FFT a second time: the DFT is its own inverse
- Solve the Vandermonde system by Gaussian elimination
- Run the same FFT with in place of , then divide every value by
- Run the FFT on the output in reverse order without any scaling
Show the answer
C. Run the same FFT with in place of , then divide every value by
The matrix of times the DFT matrix is , because the sums vanish for . So the inverse is an FFT with inverted roots and a final division by : still .
You multiply a polynomial of degree 5 by one of degree 9 with a radix-2 FFT. What is the smallest transform length that works?
- 8
- 10
- 32
- 16
Show the answer
D. 16
The product has degree 14, so 15 coefficients, and the transform needs at least 15 points; the next power of 2 is 16. A shorter transform computes a cyclic convolution, in which high coefficients wrap around onto low ones.
What makes the prime convenient for the number-theoretic transform?
- , so the integers modulo contain elements of order for every , playing the role of
- It is the largest prime below
- Every nonzero residue modulo is a root of unity of order
- Arithmetic modulo needs no multiplications
Show the answer
A. , so the integers modulo contain elements of order for every , playing the role of
Modulo a prime there is a primitive root (here ), and has order exactly whenever divides . With dividing , every power-of-2 length up to has its root of unity, and the halving lemma holds exactly, with no rounding.
Further reading
- J. W. Cooley & J. W. Tukey, "An algorithm for the machine calculation of complex Fourier series," Mathematics of Computation 19 (1965), 297–301.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 30; the iterative FFT is in §30.3 of the 3rd edition (2009).
- M. T. Heideman, D. H. Johnson & C. S. Burrus, "Gauss and the history of the fast Fourier transform," IEEE ASSP Magazine 1(4) (1984), 14–21.
- P. Clifford & R. Clifford, "Simple deterministic wildcard matching," Information Processing Letters 101(2) (2007), 53–54.
- M. Frigo & S. G. Johnson, "The design and implementation of FFTW3," Proceedings of the IEEE 93(2) (2005), 216–231.