TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › An Iterative FFT with Bit Reversal

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 lg⁡n\lg n (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 rev(0),rev(1),…\mathrm{rev}(0), \mathrm{rev}(1), \ldots, where rev(k)\mathrm{rev}(k) reverses the lg⁡n\lg n bits of kk. For n=8n = 8:

position kk 0 1 2 3 4 5 6 7
bits of kk 000 001 010 011 100 101 110 111
rev(k)\mathrm{rev}(k) 0 4 2 6 1 5 3 7

Reversal is its own inverse, so the permutation is a set of swaps of positions kk and rev(k)\mathrm{rev}(k) for k<rev(k)k < \mathrm{rev}(k). All the reversals can be computed in Θ(n)\Theta(n) time with the recurrence rev(k)=⌊rev(⌊k/2⌋)/2⌋+(k mod 2)⋅n/2\mathrm{rev}(k) = \lfloor \mathrm{rev}(\lfloor k/2 \rfloor) / 2 \rfloor + (k \bmod 2) \cdot n/2.

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 lg⁡n\lg n stages. In stage ss the blocks have length m=2sm = 2^s, and the butterfly inside a block pairs positions jj and j+m/2j + m/2 with twiddle factor ωmj\omega_m^j:

text
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 a

Every stage does n/2n/2 butterflies, so there are n2lg⁡n\frac{n}{2}\lg n 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.

python · try it yourself
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 ωnk\omega_n^k once with sines and cosines.

A circuit of depth lg⁡n\lg n

Look at the loops of lines 5 to 11: within one stage, every butterfly touches its own two positions, so all n/2n/2 butterflies of a stage are independent. The FFT is therefore a fixed circuit: lg⁡n\lg n layers of n/2n/2 butterflies each. As a fork-join program, with each stage a parallel for over its butterflies (Parallel Loops and Determinacy Races), it has work Θ(nlg⁡n)\Theta(n \lg n) and span Θ(lg⁡n)\Theta(\lg n) per stage times lg⁡n\lg n stages, Θ(lg⁡2n)\Theta(\lg^2 n), including the loop control. As a hardware circuit with one butterfly unit per node, its depth is just lg⁡n\lg n, 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 ω\omega with ωn=1\omega^n = 1 and ωn/2=−1\omega^{n/2} = -1 in a field where nn can be divided by. Modulo the prime p=998 244 353=119⋅223+1p = 998\,244\,353 = 119 \cdot 2^{23} + 1, the number 3 generates the multiplicative group, so ω=3(p−1)/n mod p\omega = 3^{(p-1)/n} \bmod p is a principal nn-th root of unity for every power of two n≤223n \le 2^{23}. Running the iterative FFT with this ω\omega and all arithmetic mod pp is the number-theoretic transform (NTT). Its results are exact residues mod pp: if all true coefficients of the product lie in [0,p)[0, p), they are recovered with no rounding at all. Division by nn becomes multiplication by n−1 mod pn^{-1} \bmod p, computed with modular exponentiation (Modular Exponentiation and Its Bit Cost).

python · try it yourself
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 pp, 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.

cpp · try it yourself
#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 (5+3x+x3)(2+7x)=10+41x+21x2+2x3+7x4(5 + 3x + x^3)(2 + 7x) = 10 + 41x + 21x^2 + 2x^3 + 7x^4 comes out exactly, with no rounding step.

Test yourself

Where does the bit-reversal permutation put the coefficient a3a_3 when n=8n = 8?

  1. Position 3
  2. Position 5
  3. Position 6
  4. Position 7

How many stages and how many butterflies per stage does the iterative FFT have for n=1024n = 1024?

  1. 10 stages of 512
  2. 512 stages of 10
  3. 10 stages of 1024
  4. 1024 stages of 1

Why can the butterflies of one stage run in parallel?

  1. They use the same twiddle factor
  2. Each butterfly reads and writes its own two positions, disjoint from the others
  3. Because the array is sorted
  4. Because the stage is the last one

What does the number-theoretic transform gain over the complex FFT?

  1. A better asymptotic running time
  2. Exact results, as long as the true coefficients lie in [0,p)[0, p)
  3. It works for any nn, not only powers of 2
  4. It needs no roots of unity