Skip to content

Whisper’s audio frontend takes a Fourier transform of every 25 ms frame of audio: 3000 frames of 400 samples for each 30 s clip. Multiplying each frame by a 400×400400 \times 400 DFT matrix costs 160000 complex multiplies per frame; an FFT does it in about 4000. More importantly, 400 is not a power of two, so the radix-2 FFT of most textbooks cannot transform it at all, and padding to 512 changes the frequencies of the bins and breaks parity with Whisper.

Concepts from other sections (6)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

This section builds the transform that the STFT of Sampling, Nyquist, windows, and the STFT and the perceptual hash of an image deduplication pipeline both stand on, and it matches numpy to within a rounding bound that grows like log⁡n\log n. You will derive the DFT as a unitary change of basis, the convolution theorem, the mixed-radix Cooley-Tukey split, the half-size real FFT, and the DCT-II, and work a four-point transform by hand. The section draws on roots of unity from Trigonometry, rotations, complex numbers, and Euler’s formula, on unitary matrices from Orthogonality, Householder QR, and orthogonal initialization, and on error bounds that grow with log⁡n\log n from Error analysis, condition numbers, and tolerance budgets.

The reference implementation is python/tinyllm/sig/fft.py, with its interface in course/contracts/py/tinyllm/sig/fft.pyi. It provides dft_matrix, a mixed-radix fft (radices 4, 2, 3, 5) and ifft, rfft and irfft from one half-size complex FFT, fft_convolve (the convolution theorem), and dct2_ortho (the DCT-II via an FFT). As you read, try to predict why each reshape, twiddle, and sign is what it is.

Learning objectives

  • Show that W/nW/\sqrt{n} is unitary and use it to derive Parseval’s identity and the inverse DFT.
  • Derive the Cooley-Tukey split for any radix and implement a mixed-radix FFT for n=2a3b5cn = 2^a 3^b 5^c.
  • Compute a real signal’s n/2+1n/2 + 1 bins from one complex FFT of size n/2n/2.
  • Use the convolution theorem with the right zero padding to compute linear convolution.
  • Compute the orthonormal DCT-II with one FFT using Makhoul’s reordering.
SymbolMeaningType / shape
nntransform lengthint
ωn=e−2πi/n\omega_n = e^{-2\pi i/n}primitive nn-th root of unitycomplex
WW, Wkj=ωnkjW_{kj} = \omega_n^{kj}DFT matrixcomplex128[n, n]
X=WxX = Wxspectrum of xxcomplex128[n]
pp, m=n/pm = n/pradix and subsequence lengthints
YrY_rDFT of the subsequence x[r],x[r+p],…x[r], x[r+p], \dotscomplex128[m]
h=n/2h = n/2half length for the real FFTint
ε\varepsilonfloat64 machine epsilon, 2−522^{-52}float

The DFT writes nn samples as coefficients of nn complex sinusoids, X[k]=∑j=0n−1x[j] ωnjk,x[j]=1n∑k=0n−1X[k] ωn−jk.X[k] = \sum_{j=0}^{n-1} x[j]\, \omega_n^{jk}, \qquad x[j] = \frac{1}{n} \sum_{k=0}^{n-1} X[k]\, \omega_n^{-jk}. The rows of WW are orthogonal: ∑jωnjkωnjl‾=∑jωnj(k−l)\sum_j \omega_n^{jk} \overline{\omega_n^{jl}} = \sum_j \omega_n^{j(k-l)}, a geometric series of roots of unity that is nn if k=lk = l and 0 otherwise. So U=W/nU = W/\sqrt{n} satisfies UHU=IU^H U = I: it is unitary, it keeps lengths, and that is Parseval’s identity ∑∣x∣2=1n∑∣X∣2\sum |x|^2 = \frac1n \sum |X|^2.

The inverse is the conjugate transform: x=WXˉ‾/nx = \overline{W \bar{X}}/n, which is how ifft reuses fft. dft_matrix reduces kj mod nkj \bmod n before computing the phase, so every entry is evaluated at an angle in [0,2π)[0, 2\pi).

The reason the DFT matters beyond spectra is what it does to convolution. For circular convolution (a⊛b)[j]=∑la[l] b[(j−l) mod n](a \circledast b)[j] = \sum_l a[l]\, b[(j - l) \bmod n], the DFT turns convolution into a product: DFT⁡(a⊛b)=DFT⁡(a)⋅DFT⁡(b)\operatorname{DFT}(a \circledast b) = \operatorname{DFT}(a) \cdot \operatorname{DFT}(b). Linear convolution, what numpy.convolve computes, has length L=len(a)+len(b)−1L = \text{len}(a) + \text{len}(b) - 1. Padding both inputs with zeros to any m≥Lm \ge L makes the wrap-around terms vanish, so the circular result equals the linear one. fft_convolve picks the smallest m≥Lm \ge L whose prime factors are 2, 3, 5.

All of this is only useful if the transform is fast. Split xx into pp interleaved subsequences xr[t]=x[r+pt]x_r[t] = x[r + pt], t<m=n/pt < m = n/p, with DFTs YrY_r of size mm. Writing k=qm+k′k = qm + k' with 0≤k′<m0 \le k' < m, 0≤q<p0 \le q < p: X[qm+k′]=∑r=0p−1ωprq(ωnrk′ Yr[k′]).X[qm + k'] = \sum_{r=0}^{p-1} \omega_p^{rq} \Big( \omega_n^{rk'}\, Y_r[k'] \Big). So the size-nn DFT is pp size-mm DFTs, a multiply by the twiddle factors ωnrk′\omega_n^{rk'}, and a size-pp DFT for each k′k'. Recursing until m=1m = 1 costs O(n∑pi)O(n \sum p_i) operations, O(nlog⁡n)O(n \log n) for small radices.

With radices 4, 2, 3, 5 every n=2a3b5cn = 2^a 3^b 5^c works: 400=4⋅4⋅5⋅5400 = 4 \cdot 4 \cdot 5 \cdot 5, Whisper’s frame. A size with another prime factor (7, 11, …) is a ValueError, not a silent O(n2)O(n^2) fallback. Each level adds a few roundings, so the error grows like log⁡n\log n: a correct implementation stays within 8log⁡2(max⁡(n,2)) ε ∥x∥28 \log_2(\max(n, 2))\, \varepsilon\, \|x\|_2 per entry.

Audio samples are real, and real signals have redundant spectra. If xx is real, X[n−k]=X[k]‾X[n - k] = \overline{X[k]}, so the bins 0…n/20 \dots n/2 determine everything. Pack the even samples as real parts and the odd ones as imaginary parts, z[t]=x[2t]+i x[2t+1]z[t] = x[2t] + i\, x[2t+1], and take one complex FFT ZZ of size h=n/2h = n/2. The DFTs of the even and odd samples untangle as E[k]=12(Z[k]+Z[(h−k) mod h]‾),O[k]=−i2(Z[k]−Z[(h−k) mod h]‾),E[k] = \tfrac12\big(Z[k] + \overline{Z[(h-k) \bmod h]}\big), \qquad O[k] = -\tfrac{i}{2}\big(Z[k] - \overline{Z[(h-k) \bmod h]}\big), and X[k]=E[k]+ωnkO[k]X[k] = E[k] + \omega_n^k O[k] for k<hk < h, with the Nyquist bin X[h]=E[0]−O[0]X[h] = E[0] - O[0] because ωnh=−1\omega_n^h = -1. irfft runs the steps backwards; the imaginary parts of X[0]X[0] and X[h]X[h] must be zero for a real signal, so it drops them first, as numpy does.

One more transform rides on the FFT. A perceptual hash (pHash) takes the orthonormal DCT-II, y[k]=sk⋅2∑jx[j]cos⁡πk(2j+1)2ny[k] = s_k \cdot 2 \sum_j x[j] \cos\frac{\pi k (2j+1)}{2n} with s0=1/(4n)s_0 = \sqrt{1/(4n)} and sk=1/(2n)s_k = \sqrt{1/(2n)}. Makhoul’s trick reorders the input into v=(x0,x2,x4,…,x5,x3,x1)v = (x_0, x_2, x_4, \dots, x_5, x_3, x_1) (even samples forward, odd samples backward); then y[k]=2skRe⁡(e−iπk/(2n)V[k])y[k] = 2 s_k \operatorname{Re}\big(e^{-i\pi k/(2n)} V[k]\big) with V=FFT⁡(v)V = \operatorname{FFT}(v). The scales make the DCT matrix orthogonal, which transforming the identity confirms.

Take x=(1,2,0,−1)x = (1, 2, 0, -1), n=4n = 4, ω4=−i\omega_4 = -i. The four bins are:

kk∑jx[j](−i)jk\sum_j x[j] (-i)^{jk}X[k]X[k]
01+2+0−11 + 2 + 0 - 122
11+2(−i)+0−1⋅(i)1 + 2(-i) + 0 - 1 \cdot (i)1−3i1 - 3i
21−2+0−1⋅(−1)1 - 2 + 0 - 1 \cdot (-1)00
31+2(i)+0−1⋅(−i)1 + 2(i) + 0 - 1 \cdot (-i)1+3i1 + 3i

X[3]=X[1]‾X[3] = \overline{X[1]}, so rfft returns (2,1−3i,0)(2, 1 - 3i, 0). Parseval checks out: ∑∣x∣2=1+4+0+1=6\sum |x|^2 = 1 + 4 + 0 + 1 = 6 and 14(4+10+0+10)=6\frac14 (4 + 10 + 0 + 10) = 6.

Now through the real-FFT packing: z=(1+2i,0−i)z = (1 + 2i, 0 - i), Z=(1+i,1+3i)Z = (1 + i, 1 + 3i); then E[0]=12((1+i)+(1−i))=1E[0] = \frac12((1+i) + (1-i)) = 1, O[0]=−i2(2i)=1O[0] = -\frac i2 (2i) = 1, so X[0]=1+1=2X[0] = 1 + 1 = 2 and X[2]=1−1=0X[2] = 1 - 1 = 0.

def dft_matrix(n, unitary=False) -> NDArray: ...
def fft(x) -> NDArray: ... # last axis, n = 2^a 3^b 5^c
def ifft(X) -> NDArray: ...
def rfft(x) -> NDArray: ... # n // 2 + 1 bins, one FFT of size n/2
def irfft(X, n) -> NDArray: ...
def fft_convolve(a, b) -> NDArray: ... # == numpy.convolve(a, b)
def dct2_ortho(x, axis=-1) -> NDArray: ... # == scipy.fft.dct(x, 2, norm='ortho')

The transforms follow numpy’s conventions (a minus sign in the forward exponent, 1/n1/n on the inverse) and work on the last axis, so a batch of frames is one call. rfft requires real input of even length; irfft requires exactly h+1h + 1 bins and the output length. Sizes with prime factors other than 2, 3, and 5, empty inputs, odd or complex rfft input, and the wrong bin count raise errors, and inputs are never modified.

The implementation follows eight steps.

  1. The reference is the matrix. Everything must equal WxWx to rounding, so dft_matrix comes first: a direct, obviously correct O(n2)O(n^2) definition that the fast code is compared against. Reducing kj mod nkj \bmod n before computing the phase keeps every angle in [0,2π)[0, 2\pi), where exp is accurate.
  2. The FFT is the Cooley-Tukey split, applied recursively. For the smallest usable radix pp of nn: form the pp interleaved subsequences, transform each (recursively) at size m=n/pm = n/p, multiply by the twiddles ωnrk′\omega_n^{rk'}, and finish with a size-pp DFT across rr for every k′k'. The base case n=1n = 1 is the identity.
  3. Interleaving is a reshape and a swap. Reading xx row-major as an m×pm \times p matrix puts x[tp+r]x[tp + r] at row tt, column rr; swapping the last two axes gives a p×mp \times m array whose row rr is subsequence rr. No index arithmetic, and the recursion transforms the last axis of a batch of pp rows at once.
  4. Only sizes 2a3b5c2^a 3^b 5^c are allowed, checked up front. If any other prime divides nn, the recursion would reach a size with no radix. Checking before starting gives a clear error at the call site. Radix 4 is tried before 2 so that powers of two use fewer, larger levels.
  5. The inverse reuses the forward transform. Since W−1=W‾/nW^{-1} = \overline{W}/n, ifft⁡(X)=fft⁡(X‾)‾/n\operatorname{ifft}(X) = \overline{\operatorname{fft}(\overline X)}/n. One FFT implementation, one set of twiddles.
  6. A real FFT is a half-size complex FFT plus untangling. Pack even and odd samples into one complex signal, transform at size hh, and separate EE and OO using the conjugate symmetry of real signals. irfft inverts each step: rebuild EE and OO from XX, recombine into ZZ, inverse transform, and unpack real and imaginary parts into even and odd samples.
  7. Linear convolution needs padding. The DFT computes circular convolution. Padding both inputs to m≥len(a)+len(b)−1m \ge \text{len}(a) + \text{len}(b) - 1 leaves room for the whole result, so nothing wraps; the smallest such mm with factors 2, 3, 5 keeps the FFT applicable.
  8. The DCT-II is an FFT of a permuted input. Makhoul’s reordering makes ∑jx[j]cos⁡πk(2j+1)2n\sum_j x[j]\cos\frac{\pi k(2j+1)}{2n} equal to Re⁡(e−iπk/(2n)V[k])\operatorname{Re}(e^{-i\pi k/(2n)} V[k]), so one FFT plus a phase and a scale computes it.

Step 1, the reference matrix:

def dft_matrix(n: int, unitary: bool = False) -> NDArray:
if n < 1:
raise ValueError(f"dft_matrix: n must be >= 1, got {n}")
j = np.arange(n)
# Reduce k * j mod n before scaling: the phase stays in [0, 2 pi) and
# exp is evaluated where it is accurate.
w = np.exp(-2j * np.pi * (np.outer(j, j) % n) / n) # minus sign: numpy's forward convention
return w / np.sqrt(n) if unitary else w

Steps 2 to 4, the recursive FFT:

_RADICES = (4, 2, 3, 5)
def _radix(n: int) -> int:
"""The first radix the FFT splits n by (4 before 2); ValueError if none."""
for p in _RADICES:
if n % p == 0:
return p
raise ValueError(f"fft: n = {n} has a prime factor other than 2, 3, 5")
def _fft(x: NDArray) -> NDArray:
"""Decimation in time over the last axis of a complex array."""
n = x.shape[-1]
if n == 1:
return x.copy() # the DFT of one sample is itself
p = _radix(n)
m = n // p
lead = x.shape[:-1]
# Subsequence r holds x[r], x[r + p], x[r + 2p], ...: shape [..., p, m].
sub = _fft(np.swapaxes(x.reshape(*lead, m, p), -1, -2)) # p transforms of size m
r = np.arange(p)[:, None]
k = np.arange(m)[None, :]
tw = np.exp(-2j * np.pi * ((r * k) % n) / n) # W_n^{r k}, [p, m]
# X[q m + k] = sum_r W_p^{r q} (W_n^{r k} Y_r[k]): a size-p DFT per k.
out = np.einsum("qr,...rk->...qk", dft_matrix(p), sub * tw)
return out.reshape(*lead, n) # row q, column k -> index q m + k

The output’s last two axes are (q,k′)(q, k'), and the row-major reshape maps them to qm+k′qm + k', exactly the index in the formula. For n=400n = 400 the levels are radix 4 (to 100), 4 (to 25), 5 (to 5), 5 (to 1).

The public wrappers validate once and implement step 5:

def fft(x: NDArray) -> NDArray:
a = np.asarray(x, dtype=np.complex128)
if a.ndim == 0 or a.shape[-1] < 1:
raise ValueError("fft: need at least one sample on the last axis")
_check_size(a.shape[-1]) # strip 2, 3, 5 and require 1 to remain
return _fft(a)
def ifft(X: NDArray) -> NDArray:
a = np.asarray(X, dtype=np.complex128)
# The inverse is the conjugate transform, divided by n.
return np.conj(fft(np.conj(a))) / a.shape[-1]

Step 6, the real FFT, with a reversal trick for Z[(h−k) mod h]‾\overline{Z[(h - k) \bmod h]}:

def rfft(x: NDArray) -> NDArray:
# ... reject complex input and odd or short lengths ...
h = n // 2
# Pack: even samples as the real part, odd samples as the imaginary part.
z = fft(a[..., 0::2] + 1j * a[..., 1::2]) # [..., h]
# Reversing gives Z[h-1], ..., Z[0]; rolling by one gives Z[0], Z[h-1], ..., Z[1],
# which is Z[(h - k) mod h] for k = 0 .. h-1.
zr = np.conj(np.roll(z[..., ::-1], 1, axis=-1)) # conj(Z[(h - k) mod h])
even = 0.5 * (z + zr) # DFT of the even samples
odd = -0.5j * (z - zr) # DFT of the odd samples
k = np.arange(h)
lower = even + np.exp(-2j * np.pi * k / n) * odd # bins 0 .. h-1
nyq = even[..., :1] - odd[..., :1] # bin h: W_n^h = -1
return np.concatenate([lower, nyq], axis=-1)

The inverse runs the same algebra backwards. Given X[k]X[k] and X[h−k]‾\overline{X[h - k]}, E=12(X[k]+X[h−k]‾)E = \frac12(X[k] + \overline{X[h-k]}) and O=12(X[k]−X[h−k]‾) ωn−kO = \frac12(X[k] - \overline{X[h-k]})\,\omega_n^{-k}, and Z=E+iOZ = E + iO:

def irfft(X: NDArray, n: int) -> NDArray:
# ... require even n >= 2 and exactly h + 1 bins ...
a = a.copy() # never modify the caller's spectrum
# The DC and Nyquist bins of a real signal are real: drop any imaginary
# part, as numpy does, instead of letting it leak into the samples.
a[..., 0] = a[..., 0].real
a[..., h] = a[..., h].real
k = np.arange(h)
xk = a[..., :h]
xr = np.conj(a[..., h - k]) # conj(X[h - k]), k = 0 .. h-1
even = 0.5 * (xk + xr)
odd = 0.5 * (xk - xr) * np.exp(2j * np.pi * k / n)
z = ifft(even + 1j * odd)
out = np.empty(a.shape[:-1] + (n,))
out[..., 0::2] = z.real # unpack: real part -> even samples
out[..., 1::2] = z.imag # imaginary part -> odd samples
return out

Steps 7 and 8, convolution and the DCT:

def fft_convolve(a: NDArray, b: NDArray) -> NDArray:
# ... two non-empty 1-D arrays ...
full = a.size + b.size - 1
# Zero-pad past the full length so the circular convolution the DFT
# computes never wraps around: then it equals the linear one.
m = _fast_size(full) # smallest m >= full with factors 2, 3, 5
fa = fft(np.pad(a.astype(np.complex128), (0, m - a.size)))
fb = fft(np.pad(b.astype(np.complex128), (0, m - b.size)))
y = ifft(fa * fb)[:full]
if not (np.iscomplexobj(a) or np.iscomplexobj(b)):
return y.real.copy() # real inputs: drop rounding-level imaginary parts
return y
def dct2_ortho(x: NDArray, axis: int = -1) -> NDArray:
a = np.moveaxis(np.asarray(x, dtype=np.float64), axis, -1)
# ... n >= 1 ...
# Makhoul: even samples forward, odd samples backward, then one FFT.
v = np.concatenate([a[..., 0::2], a[..., 1::2][..., ::-1]], axis=-1)
vf = fft(v)
k = np.arange(n)
# scipy's unnormalized DCT-II: y[k] = 2 Re(exp(-i pi k / 2n) V[k]).
y = 2.0 * (vf * np.exp(-1j * np.pi * k / (2 * n))).real
scale = np.full(n, np.sqrt(1.0 / (2 * n)))
scale[0] = np.sqrt(1.0 / (4 * n)) # norm='ortho' makes the DCT matrix orthogonal
return np.moveaxis(y * scale, -1, axis)

dct2_ortho works along any axis, so a 2-D DCT of a 32 x 32 block, as pHash needs, can be computed as dct2_ortho(dct2_ortho(block, axis=0), axis=1).

The full solution is fft.py.

Each recursion level does O(np)O(np) work (the size-pp DFTs) plus O(n)O(n) twiddles, and there are log⁡pn\log_p n levels, so n=400n = 400 costs about 400⋅(4+4+5+5)=7200400 \cdot (4 + 4 + 5 + 5) = 7200 complex multiply-adds instead of 160 000160\,000. rfft halves that again by transforming n/2n/2 points. Memory is O(n)O(n) per level.

Mixed radix beats radix 2 with padding because padding a 400-sample frame to 512 changes the bin frequencies from multiples of 16000/400=4016000/400 = 40 Hz to multiples of 31.2531.25 Hz, which is a different spectrogram than the one Whisper was trained on. Supporting radices 3 and 5 gives the exact transform for every size this book uses.

Other primes raise rather than fall back to O(n2)O(n^2). A silent quadratic path turns a misconfigured frame length into a slow pipeline with no error. Production libraries handle large primes with Bluestein’s algorithm; here the sizes are known, so an error is more useful.

The recursion uses dft_matrix(p) for the small DFT because for p≤5p \le 5 a dense p×pp \times p matrix product is the simplest correct butterfly, and einsum vectorizes it over every k′k' and every batch row. Hand-written radix-4 butterflies would be faster but would duplicate the math.

On accuracy, each level adds a few roundings, so the error grows like log⁡n\log n, about 8log⁡2n ε ∥x∥28 \log_2 n\,\varepsilon\,\|x\|_2 per entry. The direct matrix product, by contrast, accumulates nn terms per entry.

A correct implementation reproduces the hand example’s spectrum, its rfft half, and Parseval, which fixes the sign and packing conventions. The DFT matrix must be unitary (UHU=IU^H U = I for several nn), match the formula entry by entry, and reject n=0n = 0. fft must match numpy within the log⁡n\log n bound on 19 sizes up to 512, including 240 and 400, and on a batch, which is what STFT parity rests on; it must also equal WxWx on mixed-radix sizes, since the FFT is only fast multiplication. rfft and irfft must match numpy for every even size, with irfft dropping imaginary DC and Nyquist parts. Round trips must hold: ifft(fft(x)) = x, Parseval, and irfft(rfft(r)) = r. fft_convolve must equal numpy.convolve, including lengths that need padding to 12. dct2_ortho must match scipy’s orthonormal DCT-II on vectors and a 32 x 32 block and be orthogonal. Unsupported sizes (prime factors 7 and 11), empty input, odd or complex rfft input, and the wrong bin count must raise, with inputs untouched, so misconfigured frames fail loudly.

The usual mistakes:

PitfallSymptomHow the solution avoids it
twiddle factors with +2πi+2\pi ievery size above 4 wrong; spectra mirroredevery forward exponent is −2πi-2\pi i, matching dft_matrix
Nyquist bin as E[0]+O[0]E[0] + O[0]the last rfft bin wrongnyq = even[..., :1] - odd[..., :1], since ωnh=−1\omega_n^h = -1
ifft without the 1/n1/nround trips scaled by nnifft divides the conjugate transform by a.shape[-1]
multiplying unpadded spectracircular wrap-around; wrong lengthpads both inputs to _fast_size(len(a) + len(b) - 1) and slices to full (step 7)
scaling bin 0 like the others in the DCTthe DC coefficient 2\sqrt2 too large; not orthogonalscale[0] = sqrt(1 / (4n))
keeping an imaginary DC part in irffta spurious alternating componentirfft sets bins 0 and hh to their real parts first
splitting into contiguous blocks instead of interleaved subsequencesa different transform that still has the right shapereshapes to (m, p) and swaps axes (step 3)
accepting n=0n = 0 in dft_matrixan empty matrix instead of an errorraises for n < 1
accepting extra bins in irfftthe trailing bins silently ignoredrequires exactly h+1h + 1 bins
accepting complex input in rfftthe imaginary part discardedrfft rejects complex input with np.iscomplexobj

The next section, Sampling, Nyquist, windows, and the STFT, runs rfft on every frame in stft and irfft in istft. The image deduplication stage of the corpus pipeline in Data Engineering computes pHash with a 32 x 32 dct2_ortho. The chapter’s problem set works DFT properties, the convolution theorem, and FFT operation counts by hand.

Each piece has a production counterpart:

Solution pieceProduction equivalentWhat it addsWhere to look
fftpocketfft (numpy, scipy)radices up to 11 plus Bluestein for large primes, cache-friendly plansnumpy/fft/_pocketfft_umath.cpp
fftFFTWplans tuned by measurement (“wisdom”), codelets generated by genfftFrigo and Johnson, Proc. IEEE 2005
rfft in Rustrustfft and realfft (used by the Rust serving engine)SIMD butterflies; the same half-size packingrealfft crate docs
fft in Can optional C kernelmixed-radix real FFT plans for the Whisper frontendc/src/kernels/audio.c
  • Cooley and Tukey, “An algorithm for the machine calculation of complex Fourier series” (1965).
  • Van Loan, Computational Frameworks for the Fast Fourier Transform, ch. 1 to 2.
  • Makhoul, “A fast cosine transform in one and two dimensions” (1980).
  • DFT: multiplication by Wkj=ωnkjW_{kj} = \omega_n^{kj}, writing nn samples as coefficients of nn complex sinusoids.
  • Parseval’s identity: ∑∣x∣2=1n∑∣X∣2\sum |x|^2 = \frac1n \sum |X|^2, a consequence of W/nW/\sqrt n being unitary.
  • Twiddle factor: the phase ωnrk′\omega_n^{rk'} that aligns subsequence transforms before the final size-pp DFT.
  • Radix: the factor pp by which one FFT level splits the length.
  • Conjugate symmetry: X[n−k]=X[k]‾X[n-k] = \overline{X[k]} for real input, which lets rfft keep only n/2+1n/2 + 1 bins.
  • DCT-II: the cosine transform ∑jx[j]cos⁡πk(2j+1)2n\sum_j x[j]\cos\frac{\pi k(2j+1)}{2n}; orthonormal with the scales sks_k.
  • The DFT is multiplication by Wkj=e−2πikj/nW_{kj} = e^{-2\pi i kj/n}; W/nW/\sqrt{n} is unitary, so the transform keeps energy (Parseval) and its inverse is the conjugate transform divided by nn.
  • An FFT splits xx into pp interleaved subsequences, transforms them, and recombines them with twiddle factors and one size-pp DFT; mixed radices cover n=400=4⋅4⋅5⋅5n = 400 = 4 \cdot 4 \cdot 5 \cdot 5.
  • A real signal’s spectrum is conjugate symmetric, so rfft computes n/2+1n/2 + 1 bins from one complex FFT of size n/2n/2.
  • The convolution theorem gives circular convolution; zero-padding to ≥\ge len(a) + len(b) - 1 makes it linear.
  • The orthonormal DCT-II is a reordered FFT.
  1. Why does x.reshape(*lead, m, p) followed by swapaxes give the interleaved subsequences rather than contiguous blocks?
    Answer A row-major $m \times p$ view puts $x[tp + r]$ at $(t, r)$: column $r$ collects every $p$-th sample starting at $r$. Swapping makes that column a row. Reshaping to $(p, m)$ directly would give contiguous blocks $x[rm \dots rm + m - 1]$, a different (and wrong) decomposition with the same shape.
  2. Why is the Nyquist bin E[0]−O[0]E[0] - O[0] and not E[0]+O[0]E[0] + O[0]?
    Answer $X[k] = E[k] + \omega_n^k O[k]$ with $E$ and $O$ periodic in $h$. At $k = h$, $E[h] = E[0]$, $O[h] = O[0]$, and $\omega_n^h = e^{-i\pi} = -1$. In the hand-worked example this gives $X[2] = 1 - 1 = 0$.
  3. Why does irfft discard the imaginary parts of bins 00 and hh?
    Answer For a real signal those bins are real ($X[0] = \sum x$, $X[h] = \sum (-1)^j x[j]$). Any imaginary part there has no real signal behind it, and passing it through the inverse would add a spurious component (an alternating pattern for the Nyquist bin). numpy drops it, so the solution does too.
  4. Lengths 5 and 4 give a full convolution of length 8. Why not transform at size 5 and multiply?
    Answer The DFT product is circular convolution of length 5: the last 3 terms of the linear result wrap around and add onto the first 3. Padding to $m \ge 8$ leaves room for every term, so nothing wraps and the first 8 entries are the linear convolution.
  5. Why is scale[0] different from the other DCT scales?
    Answer The $k = 0$ basis vector is constant, $\cos 0 = 1$ everywhere, and its squared norm under the unnormalized transform is twice that of the other cosines. Scaling it by $\sqrt{1/(4n)}$ instead of $\sqrt{1/(2n)}$ gives every row unit norm, which is what makes the DCT matrix orthogonal.