TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › The Inverse FFT and Fast Polynomial Multiplication

The Inverse FFT and Fast Polynomial Multiplication

The FFT turns coefficients into values at the roots of unity in Θ(nlg⁡n)\Theta(n \lg n) time. To finish the plan of Coefficient and Point-Value Representations, we need the way back: interpolation at the roots of unity. It turns out to be the same algorithm with ωn\omega_n replaced by its inverse and a division by nn. With both directions fast, two polynomials of degree-bound nn can be multiplied in Θ(nlg⁡n)\Theta(n \lg n) time, and so can two nn-digit integers, up to the care needed with floating-point rounding.

Inverting the DFT

The DFT is y=Vnay = V_n a with (Vn)kj=ωnkj(V_n)_{kj} = \omega_n^{kj}. Its inverse is almost the same matrix.

Theorem. For j,k=0,…,n−1j, k = 0, \ldots, n - 1, the (j,k)(j, k) entry of Vn−1V_n^{-1} is ωn−kj/n\omega_n^{-kj}/n.

Proof

Let WW have entries Wjk=ωn−kj/nW_{jk} = \omega_n^{-kj}/n and compute the entry (j,j′)(j, j') of WVnW V_n:

(WVn)jj′=∑k=0n−1ωn−kjn ωnkj′=1n∑k=0n−1(ωnj′−j)k.(W V_n)_{jj'} = \sum_{k=0}^{n-1} \frac{\omega_n^{-kj}}{n}\, \omega_n^{kj'} = \frac{1}{n} \sum_{k=0}^{n-1} \left(\omega_n^{j' - j}\right)^k .

If j′=jj' = j, every term is 1 and the result is 1. Otherwise −(n−1)≤j′−j≤n−1-(n-1) \le j' - j \le n - 1 is not a multiple of nn, and the summation lemma (Roots of Unity and the DFT) makes the sum 0. So WVn=IW V_n = I.

Therefore

aj=1n∑k=0n−1yk ωn−kj,j=0,…,n−1.a_j = \frac{1}{n} \sum_{k=0}^{n-1} y_k\, \omega_n^{-kj}, \qquad j = 0, \ldots, n - 1 .

This is a DFT of the vector yy with ωn−1\omega_n^{-1} in place of ωn\omega_n, followed by a division by nn. The recursive FFT of the previous lesson works unchanged with ωn−1\omega_n^{-1} (its roots satisfy the same lemmas), so the inverse FFT also takes Θ(nlg⁡n)\Theta(n \lg n) time: change the sign of the angle in the twiddle factor, then divide every result by nn.

Multiplying polynomials

text
FFT-MULTIPLY(a, b)                  // coefficient vectors of degree-bound n
1  N = the smallest power of 2 with N >= len(a) + len(b) - 1
2  pad a and b with zeros to length N
3  ya = FFT(a);  yb = FFT(b)                    // Theta(N lg N)
4  yc[k] = ya[k] * yb[k] for k = 0 .. N - 1      // Theta(N)
5  c = INVERSE-FFT(yc)                           // Theta(N lg N)
6  return c, rounded to the nearest integers if a and b were integers

Since N<4nN < 4n, the total time is Θ(nlg⁡n)\Theta(n \lg n). Line 6 matters: floating-point arithmetic returns values like 14.99999999999999814.999999999999998 and 10−15i10^{-15} i, and for integer inputs the true coefficients are integers, so rounding recovers them exactly as long as every error stays below 0.50.5.

python · try it yourself
import cmath, random

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

def fft_multiply(a, b):
    N = 1
    while N < len(a) + len(b) - 1:
        N *= 2
    ya = fft(a + [0] * (N - len(a)))
    yb = fft(b + [0] * (N - len(b)))
    c = fft([p * q for p, q in zip(ya, yb)], invert=True)
    raw = [v / N for v in c]
    return [round(v.real) for v in raw[:len(a) + len(b) - 1]], raw

def naive(a, b):
    c = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            c[i + j] += x * y
    return c

A, B = [5, -2, 0, 3], [1, 4, -1, 2]
c, raw = fft_multiply(A, B)
print("FFT product:  ", c)
print("naive product:", naive(A, B))
print("largest distance of a raw value from its integer:",
      "below 1e-9" if max(abs(v - round(v.real)) for v in raw) < 1e-9 else "large")

rng = random.Random(1)
for n in [100, 1000]:
    a = [rng.randint(-1000, 1000) for _ in range(n)]
    b = [rng.randint(-1000, 1000) for _ in range(n)]
    print(f"n = {n}: FFT product equals the naive product: {fft_multiply(a, b)[0] == naive(a, b)}")
FFT product:   [5, 18, -13, 15, 8, -3, 6]
naive product: [5, 18, -13, 15, 8, -3, 6]
largest distance of a raw value from its integer: below 1e-9
n = 100: FFT product equals the naive product: True
n = 1000: FFT product equals the naive product: True

Multiplying large integers

An integer in base 10 is a polynomial evaluated at x=10x = 10: 4096=6+9x+0x2+4x34096 = 6 + 9x + 0x^2 + 4x^3 at x=10x = 10. Multiplying the digit polynomials and then propagating carries gives the product of the integers. Each coefficient of the product is at most 9⋅9⋅n9 \cdot 9 \cdot n, so it fits easily, and the work is Θ(nlg⁡n)\Theta(n \lg n) for nn-digit numbers, against Θ(n2)\Theta(n^2) for schoolbook multiplication and Θ(nlg⁡3)\Theta(n^{\lg 3}) for Karatsuba's algorithm.

python · try it yourself
import cmath, random

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

def multiply_digits(x, y):
    a = [int(d) for d in reversed(str(x))]
    b = [int(d) for d in reversed(str(y))]
    N = 1
    while N < len(a) + len(b):
        N *= 2
    ya, yb = fft(a + [0] * (N - len(a))), fft(b + [0] * (N - len(b)))
    c = [round((v / N).real) for v in fft([p * q for p, q in zip(ya, yb)], invert=True)]
    carry, digits = 0, []
    for v in c:                                  # propagate carries
        carry += v
        digits.append(carry % 10)
        carry //= 10
    while carry:
        digits.append(carry % 10); carry //= 10
    return int("".join(map(str, reversed(digits))))

print("4096 * 1234 =", multiply_digits(4096, 1234))
rng = random.Random(7)
x, y = rng.randrange(10**499, 10**500), rng.randrange(10**499, 10**500)
p = multiply_digits(x, y)
print("two 500-digit numbers: product has", len(str(p)), "digits, matches Python:", p == x * y)
print("first 30 digits:", str(p)[:30])
4096 * 1234 = 5054464
two 500-digit numbers: product has 1000 digits, matches Python: True
first 30 digits: 428222593237343509176374624340

Python's own integers use Karatsuba multiplication; libraries for huge numbers such as GMP switch to FFT-based methods (Schönhage-Strassen) beyond tens of thousands of digits. In 2019 Harvey and van der Hoeven gave an O(nlg⁡n)O(n \lg n) algorithm for integer multiplication in the bit model, the bound conjectured by Schönhage and Strassen in 1971.

When rounding fails

Floating-point FFTs accumulate error roughly in proportion to lg⁡n\lg n times the magnitude of the coefficients. With 53-bit doubles, products whose coefficients reach about 101510^{15} can round to the wrong integer. Two standard remedies: split each coefficient into smaller pieces (for example base 10310^3 digits, or two 16-bit halves) so the products stay small, or use the number-theoretic transform, the same algorithm in arithmetic modulo a prime pp that has nn-th roots of unity. Its results are exact; the next lesson implements it. The Signals course discusses the same convolution theorem for signals in Fast Convolution and Fast Multiplication.

In C++

FFT multiplication in C++, with the forward and inverse transforms sharing one function, checked against the naive product on random polynomials.

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

std::vector<cd> fft(const std::vector<cd>& a, int sign) {
    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, sign), y1 = fft(odd, sign);
    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, sign * 2 * PI * double(k) / double(n)) * y1[k];
        y[k] = y0[k] + t;
        y[k + n / 2] = y0[k] - t;
    }
    return y;
}

std::vector<long long> multiply(const std::vector<long long>& a, const std::vector<long long>& b) {
    size_t need = a.size() + b.size() - 1, N = 1;
    while (N < need) N *= 2;
    std::vector<cd> fa(a.begin(), a.end()), fb(b.begin(), b.end());
    fa.resize(N); fb.resize(N);
    auto ya = fft(fa, 1), yb = fft(fb, 1);
    for (size_t k = 0; k < N; k++) ya[k] *= yb[k];
    auto c = fft(ya, -1);
    std::vector<long long> out(need);
    for (size_t i = 0; i < need; i++) out[i] = std::llround(c[i].real() / double(N));
    return out;
}

int main() {
    auto c = multiply({5, -2, 0, 3}, {1, 4, -1, 2});
    std::printf("product:");
    for (long long v : c) std::printf(" %lld", v);
    std::printf("\n");
    std::mt19937 rng(1);
    for (int n : {100, 1000, 4000}) {
        std::vector<long long> a(n), b(n);
        for (auto& x : a) x = int(rng() % 2001) - 1000;
        for (auto& x : b) x = int(rng() % 2001) - 1000;
        std::vector<long long> naive(2 * n - 1, 0);
        for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) naive[i + j] += a[i] * b[j];
        std::printf("n = %4d: FFT matches naive: %s\n", n, multiply(a, b) == naive ? "yes" : "no");
    }
}
product: 5 18 -13 15 8 -3 6
n =  100: FFT matches naive: yes
n = 1000: FFT matches naive: yes
n = 4000: FFT matches naive: yes

Test yourself

How does the inverse DFT differ from the DFT?

  1. It uses ωn2\omega_n^2
  2. It uses ωn−1\omega_n^{-1} instead of ωn\omega_n and divides the results by nn
  3. It needs Θ(n2)\Theta(n^2) time
  4. It sorts the values first

To multiply two polynomials of degree-bound 300 with the FFT, what transform length NN is used?

  1. 300
  2. 512
  3. 600
  4. 1024

Why does an FFT product of integer polynomials need rounding at the end?

  1. The FFT is approximate by design
  2. Floating-point roots of unity introduce tiny errors, and the exact coefficients are integers
  3. The inverse transform divides by nn, which is not an integer
  4. Because the coefficients are negative

What is the running time of multiplying two nn-digit integers with an FFT on their digit polynomials (ignoring precision issues)?

  1. Θ(n)\Theta(n)
  2. Θ(nlg⁡n)\Theta(n \lg n)
  3. Θ(nlg⁡3)\Theta(n^{\lg 3})
  4. Θ(n2)\Theta(n^2)