The DFT and FFT for Engineers: Bins, Scaling and Amplitude
np.fft.fft(x) returns an array of complex numbers. To turn them into "the component is peak" you need three facts that textbooks often leave out: which frequency each element belongs to, how to scale the magnitudes into volts (peak, rms or power), and what the first and last elements mean. Get any of them wrong and your spectrum is off by a factor of , or . This lesson is the engineer's recipe. The definition, the properties and the FFT algorithm itself are covered in The DFT, DFT Properties and FFT in NumPy.
Bins and frequencies
For samples taken at , the DFT
correlates the record with complex sinusoids that complete exactly cycles in the record. Bin therefore sits at
where is the record length. The bin spacing depends only on how long you recorded, not on the sample rate. Bins are negative frequencies: belongs to . For a real signal , so the upper half is redundant and np.fft.rfft returns only bins , with np.fft.rfftfreq(N, 1/fs) giving their frequencies.
Scaling the magnitudes
A real tone that falls exactly on bin splits into two complex exponentials of amplitude , at and . Each contributes to its bin. Hence the one-sided amplitude spectrum
DC and the Nyquist bin are not doubled because they have no mirror partner. Other conventions follow from this one:
| Want | Formula (bins ) | Unit |
|---|---|---|
| peak amplitude | V | |
| rms amplitude | ||
| power of the tone | (into ) | |
| level | dBV |
Parseval ties the record's mean-square value to the bins, , which is a good check on any scaling. Tones that do not fall on a bin spread into neighbours and read low: that is leakage, handled by windows (which also change the scaling). Noise needs a density scaling: Spectral Estimation.
Worked example: reading a three-component signal
Given: , sampled at for samples.
Find: the bin spacing, the bins holding each component, their amplitudes in V peak and dBV, and the total mean-square value.
Solve: , so and the components sit in bins 0, 50 and 120. Expected: ; peak ; peak . The mean square is . The sine at appears with phase relative to a cosine.
Check: the code below reads the same values from the FFT and confirms Parseval.
import numpy as np
fs, N = 1000, 1000
t = np.arange(N) / fs
x = 0.3 + 1.2 * np.cos(2 * np.pi * 50 * t) + 0.4 * np.sin(2 * np.pi * 120 * t)
X = np.fft.rfft(x)
f = np.fft.rfftfreq(N, 1 / fs)
A = 2 * np.abs(X) / N # one-sided peak amplitude ...
A[0] /= 2 # ... except DC (and the Nyquist bin, N even)
A[-1] /= 2
print(f"bin spacing {f[1]:.1f} Hz, {len(X)} one-sided bins up to {f[-1]:.0f} Hz")
for k in np.flatnonzero(A > 1e-9):
rms = A[k] / (np.sqrt(2) if 0 < k < N // 2 else 1)
print(f"{f[k]:5.0f} Hz: {A[k]:.4f} V peak, {rms:.4f} V rms, {20 * np.log10(rms):7.2f} dBV, "
f"phase {np.degrees(np.angle(X[k])):6.1f} deg")
print(f"mean square: time domain {np.mean(x**2):.4f} V^2, from all N bins {np.sum(np.abs(np.fft.fft(x))**2) / N**2:.4f} V^2")bin spacing 1.0 Hz, 501 one-sided bins up to 500 Hz
0 Hz: 0.3000 V peak, 0.3000 V rms, -10.46 dBV, phase 0.0 deg
50 Hz: 1.2000 V peak, 0.8485 V rms, -1.43 dBV, phase 0.0 deg
120 Hz: 0.4000 V peak, 0.2828 V rms, -10.97 dBV, phase -90.0 deg
mean square: time domain 0.8900 V^2, from all N bins 0.8900 V^2
Why the FFT matters
Computing all bins directly costs complex multiplications. The fast Fourier transform (Cooley–Tukey, 1965, FFT Algorithm) factors the DFT into stages of butterflies and needs about . For a 4096-point spectrum that is million against , a factor of 683, and it is the reason spectrum analysis runs in real time on a microcontroller. The FFT gives exactly the same numbers as the DFT; it is an algorithm, not an approximation.
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(3)
x = rng.standard_normal(256)
n = np.arange(256)
W = np.exp(-2j * np.pi * np.outer(n, n) / 256) # the DFT as a 256 x 256 matrix
print(f"max |matrix DFT - FFT| = {np.max(np.abs(W @ x - np.fft.fft(x))):.1e}")
for N in (256, 1024, 4096, 65536):
direct, fast = N**2, N // 2 * int(np.log2(N))
print(f"N = {N:6d}: direct {direct:>13,d} multiplies, radix-2 FFT {fast:>9,d}, ratio {direct / fast:7.0f}")
# One-sided spectrum of the three-component signal, as a stem plot in dBV (rms)
fs, N = 1000, 1000
t = np.arange(N) / fs
x = 0.3 + 1.2 * np.cos(2 * np.pi * 50 * t) + 0.4 * np.sin(2 * np.pi * 120 * t)
A = 2 * np.abs(np.fft.rfft(x)) / N
A[0] /= 2
f = np.fft.rfftfreq(N, 1 / fs)
plt.figure(figsize=(7, 2.6))
plt.stem(f[:200], 20 * np.log10(np.maximum(A[:200] / np.sqrt(2), 1e-6)), bottom=-120)
plt.ylim(-120, 5); plt.xlabel("f (Hz)"); plt.ylabel("dBV (rms)"); plt.tight_layout(); plt.show()max |matrix DFT - FFT| = 2.2e-12
N = 256: direct 65,536 multiplies, radix-2 FFT 1,024, ratio 64
N = 1024: direct 1,048,576 multiplies, radix-2 FFT 5,120, ratio 205
N = 4096: direct 16,777,216 multiplies, radix-2 FFT 24,576, ratio 683
N = 65536: direct 4,294,967,296 multiplies, radix-2 FFT 524,288, ratio 8192
(The DC line in the plot is shown divided by like the others; DC's rms is its value, . Empty bins are clipped at for the plot; their true values are double-precision rounding noise, around .)
Practical recipe
- Choose for the bin spacing you need (), then for the band (twice the highest frequency, plus margin).
- Remove the mean if DC is not of interest (it leaks into the low bins once you window).
- Window if tones are not exactly on bins (next lessons) and correct the scaling for the window.
- Use
rfftandrfftfreqfor real data; scale with except DC and Nyquist. - Quote what you plot: peak or rms, V or dBV, the bin spacing and the window.
Guided lab: a scope's FFT and your own
Hand calculation. A generator set to , peak into a high-impedance input gives .
Simulation. Change the first program's signal to 1.0 * np.cos(2 * np.pi * 1000 * t) with fs = 10000, N = 10000: the line reads peak and .
What you would measure. A scope's FFT (most report dBV rms) shows about at , within the scope's vertical accuracy (typically to , ) and the generator's amplitude accuracy; if the generator is left in its load mode into a high-impedance input, it reads high (). Export the scope's samples and run the program on them: the two must agree once the window and scaling match (Scope FFT).
Hazards and safe setup. Generator and scope only; ground clip on the generator's ground; no mains circuits.
Pitfalls
- Forgetting to divide by (NumPy's FFT is unnormalised) or doubling DC.
- Mixing peak and rms: a discrepancy is usually that.
- Reading bins above as positive frequencies.
- Assuming more samples at the same improves the frequency resolution (only a longer record does).
Practice
- samples at : what is the bin spacing, and which bin holds ?
- A bin of a 1000-point FFT of a real signal has . What is the tone's peak amplitude (assume it is on the bin)?
- Why do bins 0 and not get the factor 2?
Answer
- ; : bin 64 exactly.
- peak.
- A real tone at splits between and ; DC and the Nyquist frequency are their own mirror images, so their whole amplitude is already in one bin.
Test yourself
The bin spacing of an FFT is determined by
- the sample rate only
- the record length :
- the number of bits
- the window
A 1.2 V peak cosine exactly on bin of an -point FFT gives
For real input, np.fft.rfft of samples returns
- 1000 bins
- 500 bins
- 501 bins
- 999 bins
A radix-2 FFT of 4096 points needs about how many complex multiplications?
- 4096
- 24 576
- 16.8 million
- 8192