An Iterative FFT with Bit Reversal
The recursive FFT copies its input into even and odd halves at every level and spends time on function calls. Production FFTs avoid both. They first permute the input into bit-reversed order, the order in which the recursion would deliver the coefficients to its leaves, and then run the butterflies level by level, bottom-up, in place in one array. This lesson derives that iterative version, shows its structure as a circuit of depth (which makes it a natural parallel algorithm), and then runs the same code in modular arithmetic, the number-theoretic transform, whose results are exact.
Bit reversal
The lesson The Recursive FFT showed that the leaves of the recursion hold the coefficients in the order , where reverses the bits of . For :
| position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| bits of | 000 | 001 | 010 | 011 | 100 | 101 | 110 | 111 |
| 0 | 4 | 2 | 6 | 1 | 5 | 3 | 7 |
Reversal is its own inverse, so the permutation is a set of swaps of positions and for . All the reversals can be computed in time with the recurrence .
Butterflies bottom-up
After the permutation, consecutive blocks of length 2 hold exactly the pairs that the deepest recursive calls would combine. Combining them gives the DFTs of length 2; combining neighbouring blocks of length 2 gives DFTs of length 4; and so on for stages. In stage the blocks have length , and the butterfly inside a block pairs positions and with twiddle factor :
ITERATIVE-FFT(a) // in place; n = len(a) is a power of 2
1 BIT-REVERSE-PERMUTE(a)
2 for s = 1 to lg n
3 m = 2^s
4 w_m = exp(2 pi i / m)
5 for start = 0 to n - 1 by m // the blocks: independent of each other
6 w = 1
7 for j = 0 to m/2 - 1
8 t = w * a[start + j + m/2]
9 u = a[start + j]
10 a[start + j] = u + t
11 a[start + j + m/2] = u - t
12 w = w * w_m
13 return aEvery stage does butterflies, so there are twiddle multiplications, as before, but with no copying and no recursion. The program builds the bit-reversal table, runs the iterative FFT, and compares it with the recursive one on the polynomial used throughout this section.
import cmath
def bit_reverse_table(n):
rev = [0] * n
for k in range(1, n):
rev[k] = rev[k // 2] // 2 + (k % 2) * (n // 2)
return rev
def iterative_fft(a, invert=False):
a, n = list(a), len(a)
rev = bit_reverse_table(n)
for k in range(n):
if k < rev[k]:
a[k], a[rev[k]] = a[rev[k]], a[k]
m = 2
while m <= n:
wm = cmath.exp((-1 if invert else 1) * 2j * cmath.pi / m)
for start in range(0, n, m):
w = 1
for j in range(m // 2):
t = w * a[start + j + m // 2]
u = a[start + j]
a[start + j], a[start + j + m // 2] = u + t, u - t
w *= wm
m *= 2
return [v / n for v in a] if invert else a
def recursive_fft(a):
n = len(a)
if n == 1:
return list(a)
y0, y1 = recursive_fft(a[0::2]), recursive_fft(a[1::2])
y = [0] * n
for k in range(n // 2):
t = cmath.exp(2j * cmath.pi * k / n) * y1[k]
y[k], y[k + n // 2] = y0[k] + t, y0[k] - t
return y
print("rev for n = 8: ", bit_reverse_table(8))
print("rev for n = 16:", bit_reverse_table(16))
a = [5, -2, 0, 3, 0, 0, 0, 0]
y = iterative_fft(a)
print("iterative FFT:", [complex(round(v.real, 4) + 0.0, round(v.imag, 4) + 0.0) for v in y])
print("agrees with the recursive FFT:", max(abs(p - q) for p, q in zip(y, recursive_fft(a))) < 1e-12)
back = iterative_fft(y, invert=True)
print("inverse gives back:", [round(v.real) for v in back])rev for n = 8: [0, 4, 2, 6, 1, 5, 3, 7]
rev for n = 16: [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]
iterative FFT: [(6+0j), (1.4645+0.7071j), (5-5j), (8.5355+0.7071j), (4+0j), (8.5355-0.7071j), (5+5j), (1.4645-0.7071j)]
agrees with the recursive FFT: True
inverse gives back: [5, -2, 0, 3, 0, 0, 0, 0]
Line 12 computes the twiddle factors by repeated multiplication, which is fast but lets rounding errors grow along each block; careful implementations precompute the table of once with sines and cosines.
A circuit of depth
Look at the loops of lines 5 to 11: within one stage, every butterfly touches its own two positions, so all butterflies of a stage are independent. The FFT is therefore a fixed circuit: layers of butterflies each. As a fork-join program, with each stage a parallel for over its butterflies (Parallel Loops and Determinacy Races), it has work and span per stage times stages, , including the loop control. As a hardware circuit with one butterfly unit per node, its depth is just , which is why FFT chips and GPU kernels follow this layout.
Exact arithmetic: the number-theoretic transform
Nothing in the FFT needs complex numbers, only an element with and in a field where can be divided by. Modulo the prime , the number 3 generates the multiplicative group, so is a principal -th root of unity for every power of two . Running the iterative FFT with this and all arithmetic mod is the number-theoretic transform (NTT). Its results are exact residues mod : if all true coefficients of the product lie in , they are recovered with no rounding at all. Division by becomes multiplication by , computed with modular exponentiation (Modular Exponentiation and Its Bit Cost).
P, G = 998244353, 3
def ntt(a, invert=False):
a, n = list(a), len(a)
rev = [0] * n
for k in range(1, n):
rev[k] = rev[k // 2] // 2 + (k % 2) * (n // 2)
for k in range(n):
if k < rev[k]:
a[k], a[rev[k]] = a[rev[k]], a[k]
m = 2
while m <= n:
wm = pow(G, (P - 1) // m, P)
if invert:
wm = pow(wm, P - 2, P) # the inverse root
for start in range(0, n, m):
w = 1
for j in range(m // 2):
t = w * a[start + j + m // 2] % P
u = a[start + j]
a[start + j], a[start + j + m // 2] = (u + t) % P, (u - t) % P
w = w * wm % P
m *= 2
if invert:
n_inv = pow(n, P - 2, P)
a = [v * n_inv % P for v in a]
return a
def ntt_multiply(a, b):
N = 1
while N < len(a) + len(b) - 1:
N *= 2
fa, fb = ntt(a + [0] * (N - len(a))), ntt(b + [0] * (N - len(b)))
return ntt([x * y % P for x, y in zip(fa, fb)], invert=True)[:len(a) + len(b) - 1]
w8 = pow(G, (P - 1) // 8, P)
print("omega_8 mod p =", w8, "; omega^4 =", pow(w8, 4, P), "= p - 1; omega^8 =", pow(w8, 8, P))
print("NTT product of 5 + 3x + x^3 and 2 + 7x:", ntt_multiply([5, 3, 0, 1], [2, 7]))
a = [(31 * i * i + 7) % 1000 for i in range(300)]
b = [(17 * i + 3) % 1000 for i in range(300)]
naive = [0] * 599
for i, x in enumerate(a):
for j, y in enumerate(b):
naive[i + j] += x * y
print("300-term product exact:", ntt_multiply(a, b) == naive, " largest coefficient:", max(naive))omega_8 mod p = 372528824 ; omega^4 = 998244352 = p - 1; omega^8 = 1
NTT product of 5 + 3x + x^3 and 2 + 7x: [10, 41, 21, 2, 7]
300-term product exact: True largest coefficient: 78179483
Competitive programmers and computer-algebra systems use the NTT for exact convolutions; for coefficients larger than , several primes are combined with the Chinese remainder theorem (The Chinese Remainder Theorem).
In C++
The iterative NTT in C++, in place on a std::vector<long long>, used to multiply two integer polynomials exactly.
#include <cstdio>
#include <utility>
#include <vector>
using ll = long long;
const ll P = 998244353, G = 3;
ll power(ll b, ll e) {
ll r = 1; b %= P;
for (; e > 0; e >>= 1, b = b * b % P) if (e & 1) r = r * b % P;
return r;
}
void ntt(std::vector<ll>& a, bool invert) {
int n = int(a.size());
for (int k = 1, j = 0; k < n; k++) { // bit-reversal permutation
int bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (k < j) std::swap(a[k], a[j]);
}
for (int m = 2; m <= n; m <<= 1) {
ll wm = power(G, (P - 1) / m);
if (invert) wm = power(wm, P - 2);
for (int start = 0; start < n; start += m) {
ll w = 1;
for (int j = 0; j < m / 2; j++) {
ll t = w * a[start + j + m / 2] % P, u = a[start + j];
a[start + j] = (u + t) % P;
a[start + j + m / 2] = (u - t + P) % P;
w = w * wm % P;
}
}
}
if (invert) { ll n_inv = power(n, P - 2); for (ll& x : a) x = x * n_inv % P; }
}
int main() {
std::vector<ll> a = {5, 3, 0, 1}, b = {2, 7};
size_t need = a.size() + b.size() - 1, N = 1;
while (N < need) N <<= 1;
a.resize(N); b.resize(N);
ntt(a, false); ntt(b, false);
for (size_t i = 0; i < N; i++) a[i] = a[i] * b[i] % P;
ntt(a, true);
std::printf("product:");
for (size_t i = 0; i < need; i++) std::printf(" %lld", a[i]);
std::printf("\n");
}product: 10 41 21 2 7
The product comes out exactly, with no rounding step.
Test yourself
Where does the bit-reversal permutation put the coefficient when ?
- Position 3
- Position 5
- Position 6
- Position 7
How many stages and how many butterflies per stage does the iterative FFT have for ?
- 10 stages of 512
- 512 stages of 10
- 10 stages of 1024
- 1024 stages of 1
Why can the butterflies of one stage run in parallel?
- They use the same twiddle factor
- Each butterfly reads and writes its own two positions, disjoint from the others
- Because the array is sorted
- Because the stage is the last one
What does the number-theoretic transform gain over the complex FFT?
- A better asymptotic running time
- Exact results, as long as the true coefficients lie in
- It works for any , not only powers of 2
- It needs no roots of unity