CodeRigor

LESSON

A Fourier transform by hand

Build the discrete Fourier transform as a matrix product, read amplitude, phase and frequency from it, and check it against NumPy and Parseval's identity.

A recording is a list of pressure readings. The Fourier transform answers a different question about the same numbers: how much of each pure frequency is in them. This lesson pairs with But what is the Fourier Transform? A visual introduction. by 3Blue1Brown and with Coding Adventure: Sound (and the Fourier Transform) by Sebastian Lague, linked under Watch & read. Between them they cover the idea in pictures and in code; here you write it as one matrix product in NumPy, without np.fft, and read amplitude, phase and the strongest frequency out of the result.

Take n samples x[0] to x[n-1]. To measure frequency k, multiply every sample by a complex wave that turns k times over the whole window, then add the products:

X[k] = Σ x[t] · e^(-2πi·k·t/n), summed over t = 0 to n-1

The exponent is a rotation: at sample t the wave has turned by k·t/n of a full circle. A signal that rotates the same way as the wave piles up in the sum, and anything else cancels. The minus sign is the usual convention and it matters later. Bin k stands for k·rate/n hertz, so the bins are rate/n apart. That spacing is the frequency resolution: a longer window gives finer bins.

Eight samples give eight bins
start / 2
For a real signal, bins 5 to 7 repeat bins 3 to 1 as complex conjugates. Bins 1 to 3 carry half of each tone's amplitude, so they are doubled. Bin 0 and bin 4 have no partner.
Eight samples give eight bins
For a real signal, bins 5 to 7 repeat bins 3 to 1 as complex conjugates. Bins 1 to 3 carry half of each tone's amplitude, so they are doubled. Bin 0 and bin 4 have no partner.

Work one by hand. For n = 4, e^(-2πi/4) = -i, so every entry of the matrix is a power of -i. Row k, column t holds (-i)^(k·t). For x = [1, 2, 3, 4], bin 1 is 1 + 2(-i) + 3(-1) + 4(i) = -2 + 2i. Bin 0 is the plain sum, 10.

Python
import numpy as np

x = np.array([1, 2, 3, 4])
k = np.arange(4)
matrix = np.exp(-2j * np.pi * np.outer(k, k) / 4)   # row k, column t
X = matrix @ x
print(np.round(X.real).astype(int).tolist(), np.round(X.imag).astype(int).tolist())

The matrix is the whole transform. The inverse uses the opposite sign in the exponent and divides by n, because each row has squared length n. Build the matrix from k·t reduced modulo n: only the fractional turn matters, and a small angle loses less precision. It holds n² entries, which is why the next lesson looks for a faster route.

Audio is real, and that gives the spectrum a mirror: X[n-k] is the complex conjugate of X[k]. Bins 0 to n // 2 hold everything. A cosine of amplitude A is split in two halves of A/2, one in bin k and one in bin n-k, so the amplitude you read is |X[k]|/n doubled. Bin 0 and, for even n, the Nyquist bin at n/2 have no partner and are not doubled. The phase is the angle of X[k]: a cosine shifted by φ shows up as phase φ.

Python
import numpy as np

n = 8
t = np.arange(n)
x = 1 + 2 * np.cos(2 * np.pi * 2 * t / n + 0.5) + 0.5 * (-1.0) ** t
X = np.exp(-2j * np.pi * np.outer(t, t) / n) @ x
amp = np.abs(X[:5]) / n
amp[1:4] *= 2
print(np.round(amp, 6).tolist(), round(float(np.angle(X[2])), 6))

The printed amplitudes are the three ingredients, 1 at DC, 2 at bin 2 and 0.5 at the Nyquist bin, and the phase is the 0.5 that went in.

To find the strongest frequency, take the largest magnitude above bin 0 and report its frequency k·rate/n. That answer can only be a multiple of the spacing. Fitting a parabola through the largest magnitude and its two neighbours gives a fractional bin. The offset is 0.5·(left - right)/(left - 2·mid + right).

A 1012 Hz tone seen through 31.25 Hz bins
256 samples at 8000 Hz, tone of amplitude 1. The bins on either side of the tone share its energy, and the tallest bin reads 0.77, not 1.
A 1012 Hz tone seen through 31.25 Hz bins
256 samples at 8000 Hz, tone of amplitude 1. The bins on either side of the tone share its energy, and the tallest bin reads 0.77, not 1.
Python
import numpy as np

rate, n, f = 8000, 256, 1012.0
x = np.sin(2 * np.pi * f * np.arange(n) / rate)
mag = np.abs(np.fft.rfft(x))          # NumPy as a stand-in, only to keep this short
k = 1 + int(np.argmax(mag[1:]))
left, mid, right = mag[k - 1 : k + 2]
shift = 0.5 * (left - right) / (left - 2 * mid + right)
print(k * rate / n, round((k + shift) * rate / n, 1))

The interpolated answer is closer than the bin, and still about 7 Hz low. The window cuts the tone off abruptly, which smears its peak into a shape that is not a parabola. That is a limit of the method, not a bug in the code.

These are the mistakes to expect. Doubling every bin including DC, or including the Nyquist bin, makes a constant offset read twice too large. Using + instead of - in the forward exponent leaves every magnitude unchanged, because the spectrum is only conjugated, so amplitude tests pass while phases and delays come out backwards. Dropping the 1/n in the inverse returns n times the signal. Reading a tone's amplitude from the nearest bin undercounts it whenever the tone sits between bins.

Verification has three independent parts: NumPy's FFT as an oracle on odd and even lengths, the properties of the transform (linearity, and a signal moved s samples later gains a factor e^(-2πi·k·s/n) in bin k), and Parseval's identity, where the energy of the samples equals the energy of the spectrum divided by n. Parseval cannot see the sign of the exponent, and none of this says that the strongest bin is the true frequency. For a tone between bins, it is not.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →