TExcelTAD

The Recursive FFT

The direct DFT spends Θ(n2)\Theta(n^2) multiplications because it evaluates the polynomial at each of the nn roots of unity separately. The fast Fourier transform shares the work between the points: it splits the polynomial into its even and odd coefficients, evaluates both halves at only n/2n/2 points (the squares of the roots, by the halving lemma) and combines the results with one multiplication per pair of outputs. This divide and conquer, popularized by Cooley and Tukey in 1965 and known in essence to Gauss, runs in Θ(nlg⁡n)\Theta(n \lg n) time.

Even and odd parts

Let nn be a power of 2 and A(x)=a0+a1x+⋯+an−1xn−1A(x) = a_0 + a_1 x + \cdots + a_{n-1}x^{n-1}. Collect the even-indexed and the odd-indexed coefficients into two polynomials of degree-bound n/2n/2:

A[0](x)=a0+a2x+a4x2+⋯+an−2 xn/2−1,A[1](x)=a1+a3x+a5x2+⋯+an−1 xn/2−1.\begin{aligned} A^{[0]}(x) &= a_0 + a_2 x + a_4 x^2 + \cdots + a_{n-2}\, x^{n/2 - 1}, \\ A^{[1]}(x) &= a_1 + a_3 x + a_5 x^2 + \cdots + a_{n-1}\, x^{n/2 - 1}. \end{aligned}

Then

A(x)=A[0](x2)+x A[1](x2).A(x) = A^{[0]}(x^2) + x\, A^{[1]}(x^2).

Evaluating AA at the nn roots ωn0,…,ωnn−1\omega_n^0, \ldots, \omega_n^{n-1} therefore needs A[0]A^{[0]} and A[1]A^{[1]} at their squares, and by the halving lemma (Roots of Unity and the DFT) those squares are just the n/2n/2 roots of unity of order n/2n/2. So the two halves need exactly a DFT of size n/2n/2 each: two recursive calls.

The butterfly

Let y[0]=DFTn/2(a[0])y^{[0]} = \mathrm{DFT}_{n/2}(a^{[0]}) and y[1]=DFTn/2(a[1])y^{[1]} = \mathrm{DFT}_{n/2}(a^{[1]}), so yk[0]=A[0](ωn/2k)=A[0](ωn2k)y^{[0]}_k = A^{[0]}(\omega_{n/2}^k) = A^{[0]}(\omega_n^{2k}). For 0≤k<n/20 \le k < n/2:

yk=A(ωnk)=yk[0]+ωnk yk[1],yk+n/2=A(ωnk+n/2)=yk[0]+ωnk+n/2 yk[1]=yk[0]−ωnk yk[1],\begin{aligned} y_k &= A(\omega_n^k) = y^{[0]}_k + \omega_n^k\, y^{[1]}_k, \\ y_{k + n/2} &= A(\omega_n^{k + n/2}) = y^{[0]}_k + \omega_n^{k + n/2}\, y^{[1]}_k = y^{[0]}_k - \omega_n^k\, y^{[1]}_k, \end{aligned}

using (ωnk+n/2)2=ωn2k(\omega_n^{k + n/2})^2 = \omega_n^{2k} for the first term and ωnk+n/2=−ωnk\omega_n^{k + n/2} = -\omega_n^k for the second. Each pair of outputs costs one complex multiplication, the product t=ωnkyk[1]t = \omega_n^k y^{[1]}_k (called the twiddle factor product), plus an addition and a subtraction. This pattern, drawn as two crossing lines, is the butterfly.

text
RECURSIVE-FFT(a)                   // n = len(a) is a power of 2
1  n = len(a)
2  if n == 1
3      return a                     // the DFT of a constant is itself
4  y0 = RECURSIVE-FFT([a[0], a[2], ..., a[n-2]])
5  y1 = RECURSIVE-FFT([a[1], a[3], ..., a[n-1]])
6  for k = 0 to n/2 - 1
7      t = exp(2 pi i k / n) * y1[k]       // twiddle factor times odd part
8      y[k] = y0[k] + t
9      y[k + n/2] = y0[k] - t
10 return y

Running time

Lines 4 and 5 are two calls of half the size; lines 6 to 9 cost Θ(n)\Theta(n). So

T(n)=2T(n/2)+Θ(n)=Θ(nlg⁡n),T(n) = 2T(n/2) + \Theta(n) = \Theta(n \lg n),

the same recurrence as merge sort (The Master Theorem, case 2). Counting only the twiddle multiplications, M(n)=2M(n/2)+n/2M(n) = 2M(n/2) + n/2 with M(1)=0M(1) = 0, which solves to exactly n2lg⁡n\frac{n}{2}\lg n. (Some of them are by ω0=1\omega^0 = 1 and could be skipped.)

The program implements the recursion, counts the multiplications, and compares the results with the direct DFT. The two agree up to floating-point rounding, so the program reports the largest difference instead of printing raw floats.

python · try it yourself
import cmath

mults = 0
def fft(a):
    global mults
    n = len(a)
    if n == 1:
        return list(a)
    y0, y1 = fft(a[0::2]), fft(a[1::2])
    y = [0] * n
    for k in range(n // 2):
        t = cmath.exp(2j * cmath.pi * k / n) * y1[k]
        mults += 1
        y[k], y[k + n // 2] = y0[k] + t, y0[k] - t
    return y

def dft(a):
    n = len(a)
    return [sum(a[j] * cmath.exp(2j * cmath.pi * ((k * j) % n) / n) for j in range(n)) for k in range(n)]

a = [5, -2, 0, 3, 0, 0, 0, 0]
y = fft(a)
print("FFT of a:", [complex(round(v.real, 4) + 0.0, round(v.imag, 4) + 0.0) for v in y])
print("twiddle multiplications:", mults)

print("    n   FFT mults  (n/2) lg n   direct n^2   max |FFT - DFT| < 1e-9")
for n in [8, 64, 256, 512]:
    a = [(7 * j * j + 3) % 11 - 5 for j in range(n)]
    mults = 0
    y = fft(a)
    err = max(abs(p - q) for p, q in zip(y, dft(a)))
    print(f"{n:5} {mults:11} {n // 2 * (n.bit_length() - 1):11} {n * n:12}   {err < 1e-9}")
FFT of a: [(6+0j), (1.4645+0.7071j), (5-5j), (8.5355+0.7071j), (4+0j), (8.5355-0.7071j), (5+5j), (1.4645-0.7071j)]
twiddle multiplications: 12
    n   FFT mults  (n/2) lg n   direct n^2   max |FFT - DFT| < 1e-9
    8          12          12           64   True
   64         192         192         4096   True
  256        1024        1024        65536   True
  512        2304        2304       262144   True

The values for the first vector match the direct DFT of the previous lesson. At n=512n = 512 the FFT uses 2304 twiddle multiplications against 262,144 for the direct transform, more than a hundred times fewer, and the factor 2n/lg⁡n2n/\lg n keeps growing with nn.

Following the recursion

Which coefficients end up together at the bottom of the recursion? Each level separates even and odd positions, so after lg⁡n\lg n levels the leaves are in bit-reversed order of their indices. For n=8n = 8 that order is 0,4,2,6,1,5,3,70, 4, 2, 6, 1, 5, 3, 7: index 1=00121 = 001_2 sits at position 1002=4100_2 = 4, and so on. The program prints the subarrays at every level.

python · try it yourself
def split_levels(idx, depth=0, levels=None):
    levels = levels if levels is not None else {}
    levels.setdefault(depth, []).append(idx)
    if len(idx) > 1:
        split_levels(idx[0::2], depth + 1, levels)
        split_levels(idx[1::2], depth + 1, levels)
    return levels

for depth, groups in split_levels(list(range(8))).items():
    print(f"level {depth}:", "  ".join(str(g) for g in groups))
leaves = [g[0] for g in split_levels(list(range(8)))[3]]
print("leaf order:", leaves, " bit-reversed indices:", [int(f"{i:03b}"[::-1], 2) for i in range(8)])
level 0: [0, 1, 2, 3, 4, 5, 6, 7]
level 1: [0, 2, 4, 6]  [1, 3, 5, 7]
level 2: [0, 4]  [2, 6]  [1, 5]  [3, 7]
level 3: [0]  [4]  [2]  [6]  [1]  [5]  [3]  [7]
leaf order: [0, 4, 2, 6, 1, 5, 3, 7]  bit-reversed indices: [0, 4, 2, 6, 1, 5, 3, 7]

The leaf order is exactly the bit-reversal of 0,…,70, \ldots, 7. The iterative FFT of An Iterative FFT with Bit Reversal starts by putting the coefficients into this order and then runs the butterflies bottom-up, without recursion or array copies.

In C++

The recursive FFT in C++. The input is a std::vector<std::complex<double>>; each call copies the even and odd halves, as in the pseudocode.

cpp · try it yourself
#include <cmath>
#include <complex>
#include <cstdio>
#include <vector>
using cd = std::complex<double>;

long long mults = 0;

std::vector<cd> fft(const std::vector<cd>& a) {
    size_t n = a.size();
    if (n == 1) return a;
    std::vector<cd> even(n / 2), odd(n / 2);
    for (size_t j = 0; j < n / 2; j++) { even[j] = a[2 * j]; odd[j] = a[2 * j + 1]; }
    auto y0 = fft(even), y1 = fft(odd);
    std::vector<cd> y(n);
    const double PI = std::acos(-1.0);
    for (size_t k = 0; k < n / 2; k++) {
        cd t = std::polar(1.0, 2 * PI * double(k) / double(n)) * y1[k];
        mults++;
        y[k] = y0[k] + t;
        y[k + n / 2] = y0[k] - t;
    }
    return y;
}

double clean(double x) { double r = std::round(x * 10000) / 10000; return r == 0 ? 0.0 : r; }

int main() {
    std::vector<cd> a = {5, -2, 0, 3, 0, 0, 0, 0};
    auto y = fft(a);
    for (size_t k = 0; k < y.size(); k++)
        std::printf("y[%zu] = %8.4f %+8.4fi\n", k, clean(y[k].real()), clean(y[k].imag()));
    std::printf("twiddle multiplications: %lld\n", mults);
}
y[0] =   6.0000  +0.0000i
y[1] =   1.4645  +0.7071i
y[2] =   5.0000  -5.0000i
y[3] =   8.5355  +0.7071i
y[4] =   4.0000  +0.0000i
y[5] =   8.5355  -0.7071i
y[6] =   5.0000  +5.0000i
y[7] =   1.4645  -0.7071i
twiddle multiplications: 12

Test yourself

Which identity lets the FFT split a polynomial in two?

  1. A(x)=A[0](x)+A[1](x)A(x) = A^{[0]}(x) + A^{[1]}(x)
  2. A(x)=A[0](x2)+x A[1](x2)A(x) = A^{[0]}(x^2) + x\,A^{[1]}(x^2)
  3. A(x)=A[0](x) A[1](x)A(x) = A^{[0]}(x)\,A^{[1]}(x)
  4. A(x)=A[0](2x)+A[1](2x)A(x) = A^{[0]}(2x) + A^{[1]}(2x)

In the butterfly, how is yk+n/2y_{k + n/2} computed?

  1. yk[0]+ωnkyk[1]y^{[0]}_k + \omega_n^k y^{[1]}_k
  2. yk[0]−ωnkyk[1]y^{[0]}_k - \omega_n^k y^{[1]}_k
  3. yk[1]−yk[0]y^{[1]}_k - y^{[0]}_k
  4. ωnk(yk[0]−yk[1])\omega_n^{k} (y^{[0]}_k - y^{[1]}_k)

How many twiddle multiplications does the recursive FFT perform for n=16n = 16?

  1. 16
  2. 32
  3. 64
  4. 256

In which order do the coefficients reach the leaves of the FFT recursion for n=8n = 8?

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