The fast Fourier transform
| Problem | Compute the discrete Fourier transform of complex samples in operations |
| Devised by | Carl Friedrich Gauss (1805, unpublished); Gordon Danielson and Cornelius Lanczos (1942); James Cooley and John Tukey (1965); split radix: R. Yavne (1968), Pierre Duhamel and Henk Hollmann (1984); cache-oblivious and adaptive FFTs: Matteo Frigo and Steven Johnson (FFTW, 1998) |
| Accuracy | Relative error with accurate twiddle factors |
| Cost | Radix 2: real flops; split radix: about ; the direct DFT: |
| Read first | Preliminaries: complex numbers |
| API | Fft, BestFft, SimdFft, FftEngine1D; reference: simple_cooley_tukey, optimized_radix2, optimized_split_radix |
Overview
The FFT is a family of algorithms that compute the DFT by splitting it into smaller DFTs. The simplest, the radix-2 Cooley-Tukey algorithm, splits a transform of even length into two of length , of the even- and odd-indexed samples, and combines them with multiplications by twiddle factors . Repeating the split down to length 1 gives stages of “butterflies” each. Split radix splits more cleverly and does the fewest operations of the classical algorithms.
On modern processors the operation count is only part of the story: memory access patterns, vector instructions and the reuse of data in cache decide the speed. The production engine is a radix-2/4 Cooley-Tukey algorithm tuned for all three, and runs five to ten times faster than the textbook engines, which perform about the same number of operations.
Where it is used
The FFT is arguably the most widely used numerical algorithm of the last half century.
- Communications. OFDM in Wi-Fi, 4G/5G and digital TV is an inverse FFT in the transmitter and an FFT in the receiver.
- Spectrum analysis. Audio analysers, vibration monitoring of machines, radar and sonar processing and EEG analysis all turn time signals into spectra.
- Medical imaging and astronomy. MRI reconstructs images from Fourier-domain samples, and radio telescopes combine antennas by Fourier transform.
- Fast convolution and multiplication. Filtering long signals, correlating images and multiplying huge integers all use the FFT to replace work by .
History
Gauss devised the algorithm in 1805 to interpolate the orbits of the asteroids Pallas and Juno from observations, splitting a transform of length 12 into transforms of lengths 3 and 4; his notes were published only posthumously, in Latin, in 1866, and went unnoticed. Several later rediscoveries also passed without impact, including Danielson and Lanczos’s doubling method (1942) for X-ray crystallography. James Cooley of IBM and John Tukey of Princeton published the general algorithm in 1965, prompted by the need to detect Soviet nuclear tests from seismometer data, and it spread immediately. R. Yavne (1968) found the split-radix algorithm, rediscovered and analysed by Duhamel and Hollmann (1984). Matteo Frigo and Steven Johnson’s FFTW (1998) showed that generated, adaptively planned code could approach the hardware’s peak, and set the standard for FFT libraries.
The idea
The radix-2 Cooley-Tukey algorithm
The DFT of is
Evaluated directly, each of the outputs is a sum of terms: multiplications. The FFT reaches the same result in about by never computing the same partial sum twice.
Step 1: split the sum. Assume is even, and separate the even-indexed samples () from the odd-indexed ones ():
Step 2: recognise two smaller DFTs. Both sums involve powers of , which is exactly the of a DFT of length . So the first sum is the DFT of the even-indexed samples, call it , and the second is the DFT of the odd-indexed samples, :
Step 3: use each half twice. and are DFTs of length , so they are defined for and repeat with period . The outputs in the upper half, , therefore involve the same and . Only the factor in front changes: , since . Altogether
Each such pair of outputs costs one complex multiplication (by the twiddle factor ), one addition and one subtraction. The pattern of data flow gives the operation its name, a butterfly.
The cost. A transform of length has become two transforms of length plus butterflies. Apply the same idea to the halves, and to their halves, down to transforms of length 1, which are just the samples. If there are levels, and every level does butterflies in total. That is complex multiplications instead of : for , about instead of .
Bit reversal. The recursion sorts the samples by the parity of their index, then by the parity of half the index, and so on. The first split looks at the lowest binary digit of the index, the next at the second lowest. When the recursion bottoms out, sample has arrived at the position whose binary index is that of with its digits reversed. For the order is : for instance lands in position . An iterative FFT therefore avoids recursion altogether: it permutes the input into bit-reversed order once, and then runs the levels from the bottom up, combining transforms of length 1 into transforms of length 2, those into length 4, and so on, all in place.
Split radix
In the radix-2 formulas the even half enters without any multiplication, while the odd half needs a twiddle factor. This asymmetry can be exploited. Split radix treats the two halves differently: it leaves the even samples as one transform of length , as before, but splits the odd samples once more, into those with indices and , with transforms and of length . The four quarters of the output are then
The gain comes from the factors and that appear when the output index is shifted by a quarter or half of . Multiplying by only swaps the real and imaginary parts and changes a sign, so it costs nothing. The two products and thus serve four outputs. The total is about real operations, against for radix 2. For decades this was the lowest known count, until Johnson and Frigo (2007) shaved off a few per cent more.
Twiddle factors and accuracy
The FFT is not only faster than the direct sum but also more accurate, for the same reason: each output is reached through only butterflies, so rounding errors accumulate only logarithmically. That holds provided each twiddle factor is itself accurate to .
There is a tempting shortcut that spoils it. The twiddle factors of a stage are successive powers of one number, so many textbooks generate them by the recurrence , one multiplication each, instead of calling sine and cosine. But every multiplication adds a rounding error to a value that the next multiplication builds on, so the error of grows in proportion to , up to . The reference crate’s textbook engine does exactly that, and its error reaches at (see the figure in the chapter introduction). The other engines compute every twiddle from its exact angle and stay below .
The production engines
BestFft is an iterative decimation-in-time algorithm on bit-reversed data, made fast in five ways:
- radix-4 passes: pairs of radix-2 stages are fused, so each pass reads and writes the array once instead of twice and needs three twiddle multiplications per four outputs instead of four;
- SIMD: on x86-64 with AVX2 and FMA (detected at run time) two complex values are processed per 256-bit register, with complex
multiplication by
fmaddsub; - cache blocking: all the stages whose butterflies fit in a block are run on one block at a time, so it stays in cache;
- bandwidth-saving large passes: passes over the whole array store only and form and in registers;
- a cache-friendly permutation: the bit reversal is done in tiles, writing straight into the output with any scaling folded in.
SimdFft provides vectorised radix-2 kernels for ARM (NEON) and RISC-V as well as x86. The default Fft uses BestFft for powers of
two and Bluestein’s algorithm for every other length.
Figure 8.2. FFT speed.
The three reference engines run at 1 to 4 GFLOP/s; BestFft reaches 10 to 20, falling off once the data no longer fit in cache. The
direct DFT, at well under 0.1 GFLOP/s-equivalent, is hopeless beyond a few thousand points.
Algorithm
Iterative radix 2. Input: complex samples, transformed in place.
- Permute. Swap each element with the one whose index has the same binary digits in reverse order (each pair is swapped once).
- Combine. For each stage , with : the array now holds consecutive transforms of length . For each block of elements and each , take , the element at offset in the block, and times the element at offset ; replace the two elements by and . This is the butterfly. After the stage the array holds transforms of length .
- Scale. For the inverse transform, use the conjugate twiddle factors and divide every element by .
There are stages of butterflies: complex multiplications, and no storage beyond the array and a table of twiddle factors.
Split radix (recursive). For a transform of length :
- if is 1, return the sample; if is 2, return the sum and the difference;
- transform the even-indexed samples (length ) to get ;
- transform the samples with indices and those with indices (length each) to get and ;
- for , form and , and combine them with and by the four formulas above to produce the outputs , , and .
Implementation
The stages of the textbook engine, with its twiddle recurrence:
for s in 1..=log2n {
// m = 2^s is the size of the sub-FFTs being combined
let m = 1 << s;
// Compute the twiddle factor W_m = exp(-2*pi*i/m) for forward FFT or exp(2*pi*i/m) for inverse FFT
let theta = match self.direction {
FftDirection::Forward => -2.0 * std::f64::consts::PI / m as f64,
FftDirection::Inverse => 2.0 * std::f64::consts::PI / m as f64,
};
let wm = Complex::new(theta.cos(), theta.sin());
// Combine sub-FFTs of size m/2 into sub-FFTs of size m
for k in (0..self.size).step_by(m) {
// w starts at 1 and is multiplied by W_m in each iteration to get the next twiddle factor
let mut w = Complex::new(1.0, 0.0);
// Perform the butterfly operations for the current stage
for j in 0..(m / 2) {
// t = w * buffer[k + j + m/2] is the contribution from the second half of the sub-FFT
// u = buffer[k + j] is the contribution from the first half of the sub-FFT before the butterfly operation
let t = w * buffer[k + j + m / 2];
let u = buffer[k + j];
// Update the buffer with the results of the butterfly operation
buffer[k + j] = u + t;
buffer[k + j + m / 2] = u - t;
// Update w to the next twiddle factor for the next iteration of the butterfly operation
w *= wm;
}
}
}
The split-radix recursion:
/// Writes into `out` (of length `n`) the DFT of `input[start], input[start + stride], …`;
/// `ωᵏ` for this length is `twiddles[k · step]`, and `j` is `−i` (forward) or `+i` (inverse).
fn split_radix(input: &[Complex<f64>], start: usize, stride: usize, out: &mut [Complex<f64>], twiddles: &[Complex<f64>], step: usize, j: Complex<f64>) {
let n = out.len();
match n {
1 => out[0] = input[start],
2 => {
let (a, b) = (input[start], input[start + stride]);
out[0] = a + b;
out[1] = a - b;
}
_ => {
let (half, quarter) = (n / 2, n / 4);
{
let (u, z) = out.split_at_mut(half);
let (z1, z3) = z.split_at_mut(quarter);
split_radix(input, start, 2 * stride, u, twiddles, 2 * step, j);
split_radix(input, start + stride, 4 * stride, z1, twiddles, 4 * step, j);
split_radix(input, start + 3 * stride, 4 * stride, z3, twiddles, 4 * step, j);
}
for k in 0..quarter {
let zk = twiddles[k * step] * out[half + k];
let zk3 = twiddles[3 * k * step] * out[half + quarter + k];
let (sum, difference) = (zk + zk3, j * (zk - zk3));
let (u0, u1) = (out[k], out[k + quarter]);
out[k] = u0 + sum;
out[k + half] = u0 - sum;
out[k + quarter] = u1 + difference;
out[k + half + quarter] = u1 - difference;
}
}
}
}
A radix-4 pass of the production engine (portable version):
/// A radix-4 pass combining four length-`l` sub-transforms in every block of `4l` points.
///
/// With `W = exp(∓2πi / 4l)` and the block's four quarters `A, B, C, D` (sub-transforms of the
/// inputs congruent to 0, 2, 1, 3 modulo 4), output `j + q·l` for `q = 0..3` is
/// `A + W^2j B ± …` arranged as two radix-2 layers with a free `±i` rotation.
fn radix4_pass_scalar(data: &mut [Complex<f64>], tw: &[Complex<f64>], l: usize, inverse: bool) {
for block in data.chunks_exact_mut(4 * l) {
let (ab, cd) = block.split_at_mut(2 * l);
let (qa, qb) = ab.split_at_mut(l);
let (qc, qd) = cd.split_at_mut(l);
for j in 0..l {
// Twiddles are stored per pair of j values: [w2_j, w2_j+1, w1_j, w1_j+1, w3_j, w3_j+1].
let base = 6 * (j / 2) + (j % 2);
let (w2, w1, w3) = (tw[base], tw[base + 2], tw[base + 4]);
let a = qa[j];
let tb = qb[j] * w2;
let tc = qc[j] * w1;
let td = qd[j] * w3;
let (t0, t1, t2, t3) = (a + tb, a - tb, tc + td, rotate(tc - td, inverse));
qa[j] = t0 + t2;
qb[j] = t1 + t3;
qc[j] = t0 - t2;
qd[j] = t1 - t3;
}
}
}
plan(size, scale, direction, ordering)builds the twiddle tables;execute(input)returns a new vector.FftScaleFactorisNone,SqrtN(unitary) orN(for the inverse);FftOrdering::BitReversedaccepts input already in bit-reversed order.- The reference split-radix engine replaced an earlier engine of the same name, which repeated its first stage and returned wrong results; its tests had computed the error without checking it.
In practice
//! The FFT: textbook engines and the production engine, on the spectrum of a two-tone signal.
//!
//! Run with `cargo run -p lib_jsl_ffts_reference --example fft_engines`.
use lib_jsl_ffts::{Fft, FftDirection, FftEngine1D, FftOrdering, FftScaleFactor};
use lib_jsl_ffts_reference::{optimized_radix2::OptimizedRadix2FFT, optimized_split_radix::OptimizedSplitRadixFFT, simple_cooley_tukey::SimpleCooleyTukeyFFT};
use num_complex::Complex;
fn main() {
// One second of a 50 Hz and a 120 Hz tone sampled at 1024 Hz.
let (n, rate) = (1024usize, 1024.0);
let x: Vec<Complex<f64>> = (0..n)
.map(|k| {
let t = k as f64 / rate;
Complex::new((2.0 * std::f64::consts::PI * 50.0 * t).sin() + 0.5 * (2.0 * std::f64::consts::PI * 120.0 * t).cos(), 0.0)
})
.collect();
let mut fft = Fft::new();
fft.plan(n, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
let spectrum = fft.execute(&x).unwrap();
// Bin k is the frequency k · rate / n = k Hz; a real tone of amplitude a gives |X_k| = a n / 2.
let mut peaks: Vec<(usize, f64)> = (0..n / 2).map(|k| (k, spectrum[k].norm() * 2.0 / n as f64)).filter(|p| p.1 > 0.1).collect();
peaks.sort_by(|a, b| b.1.total_cmp(&a.1));
println!("peaks (Hz, amplitude): {peaks:.3?}");
// Every engine implements FftEngine1D and computes the same transform.
let mut engines: Vec<(&str, Box<dyn FftEngine1D>)> = vec![
("textbook radix 2", Box::new(SimpleCooleyTukeyFFT::new())),
("radix 2, exact twiddles", Box::new(OptimizedRadix2FFT::new())),
("split radix", Box::new(OptimizedSplitRadixFFT::new())),
];
for (name, engine) in engines.iter_mut() {
engine.plan(n, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard).unwrap();
let y = engine.execute(&x).unwrap();
let diff = y.iter().zip(&spectrum).map(|(a, b)| (a - b).norm()).fold(0.0, f64::max);
println!("{name:>24}: max difference from Fft {diff:.1e}");
}
// The inverse transform with 1/n scaling recovers the signal.
let mut inverse = Fft::new();
inverse.plan(n, FftScaleFactor::N, FftDirection::Inverse, FftOrdering::Standard).unwrap();
let back = inverse.execute(&spectrum).unwrap();
println!("round trip error {:.1e}", back.iter().zip(&x).map(|(a, b)| (a - b).norm()).fold(0.0, f64::max));
}
Strengths
- and : fast and accurate.
- Powers of two run at 10 to 20 GFLOP/s on one core (
cargo bench -p lib_jsl_fftscompares the engines with RustFFT); any length is supported.
Weaknesses
- Non-power-of-two lengths go through Bluestein’s algorithm, several times slower than a mixed-radix FFT would be for lengths with small prime factors.
- One-dimensional engines return a new vector (no in-place API).
Exercises
- Count the real flops of radix-2 and split-radix FFTs for and .
- Show that the in-place radix-2 algorithm reads its input in bit-reversed order.
- Measure the error of the textbook engine for and fit it to . Then replace the recurrence by exact twiddles and measure again.
- Use the FFT to multiply two polynomials of degree 1000, and check against direct multiplication.
- Compute the DFT of a sampled sine whose frequency is not an integer number of cycles, and explain the spectral leakage.
Hints and answers
- A radix-2 FFT has butterflies (12 for , 32 for ). Each butterfly with a general twiddle costs one complex multiplication (6 real flops) and two complex additions (4 real flops); count the trivial twiddles separately to see how much they save. The split-radix algorithm needs real flops: 56 for and 168 for .
- The decimation-in-time algorithm splits into even and odd samples at each stage; after stages, the sample at index ends up in the position given by the bit-reversal of , so the input must be read in that order.
- A recurrence for the twiddles accumulates rounding error, so the error grows roughly in proportion to ; with exact (directly computed) twiddles the growth is only about .
- Pad both coefficient vectors to a power of two above 2001, transform, multiply pointwise, transform back, and round; the result matches direct convolution to the extent allowed by rounding.
- A sine with a non-integer number of cycles is not periodic in the window, so the implicit periodic extension has a jump. Its spectrum is the sinc-shaped kernel of the window sampled off its peak, which spreads energy over all bins (leakage).
Further reading
- J. W. Cooley and J. W. Tukey, “An algorithm for the machine calculation of complex Fourier series”, Mathematics of Computation 19 (1965) 297–301.
- M. T. Heideman, D. H. Johnson and C. S. Burrus, “Gauss and the history of the fast Fourier transform”, IEEE ASSP Magazine 1 (1984) 14–21.
- P. Duhamel and H. Hollmann, “Split radix FFT algorithm”, Electronics Letters 20 (1984) 14–16.
- M. Frigo and S. G. Johnson, “The design and implementation of FFTW3”, Proceedings of the IEEE 93 (2005) 216–231.
- C. Van Loan, Computational Frameworks for the Fast Fourier Transform, SIAM, 1992.