AnyLearn
All lessons
Mathintermediate

Reading a Spectrum Without Fooling Yourself

A spectrum shows you artefacts of the analysis alongside the signal, and telling them apart is a learnable skill. This lesson covers spectral leakage, what windows buy and what they cost, why zero-padding does not add resolution, and the hard trade a spectrogram forces between knowing when and knowing what.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

The assumption nobody tells you about

The DFT does not analyse the signal you recorded. It analyses the infinite signal you would get by repeating your window end to end, forever. That is not an interpretation, it is what the basis functions are: sinusoids with a whole number of cycles in the window, which is the only way they can be periodic in it.

If your tone happens to complete a whole number of cycles inside the window, the repetition is seamless and everything works. If it does not, the wrap-around creates a discontinuity that was never in your data, and the transform faithfully reports the broad spectrum of that artificial jump.

Key idea: Leakage is not measurement noise and not a bug. It is the correct spectrum of a signal you did not intend to analyse: your window, tiled.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. The assumption nobody tells you about

The DFT does not analyse the signal you recorded. It analyses the infinite signal you would get by repeating your window end to end, forever. That is not an interpretation, it is what the basis functions are: sinusoids with a whole number of cycles in the window, which is the only way they can be periodic in it.

If your tone happens to complete a whole number of cycles inside the window, the repetition is seamless and everything works. If it does not, the wrap-around creates a discontinuity that was never in your data, and the transform faithfully reports the broad spectrum of that artificial jump.

Key idea: Leakage is not measurement noise and not a bug. It is the correct spectrum of a signal you did not intend to analyse: your window, tiled.

2. How much difference half a bin makes

Take a 64-point DFT of a pure sine, with no window applied, and move the tone by half a bin.

Tone positionNeighbouring binBin 12 away
exactly on bin 8-305 dB (numerical zero)-311 dB
on bin 8.5-0.4 dB-29 dB

Exactly on a bin, the spectrum is one clean spike and everything else is floating-point dust. Half a bin off, the energy smears across the entire spectrum: the neighbour is barely lower than the peak, and a bin twelve away, a fifth of the way across the whole band, still sits only 29 dB down.

Nothing about the signal changed. A pure sine is a pure sine. The entire difference is where it landed relative to an arbitrary grid, and in real data you never get to choose.

3. Windows: taper the edges so the wrap is smooth

The discontinuity comes from the ends of the window not matching. So multiply the signal by a shape that falls smoothly to zero at both ends before transforming. Whatever the wrap does now, it does it to nothing.

import numpy as np

n = np.arange(64)
x = np.sin(2*np.pi*8.5*n/64)          # deliberately between bins

raw = np.abs(np.fft.rfft(x))
win = np.abs(np.fft.rfft(x * np.hanning(64)))

Measured on that same off-bin tone, the level twelve bins away drops from -29.4 dB unwindowed to -73.3 dB with a Hann window. That is a factor of about 160 in amplitude, for one extra multiply per sample.

Definition: A window is a taper applied before the transform. Not applying one is still a choice: it is the rectangular window, and it is the worst-behaved of the family.

4. What the common windows actually do

Peak sidelobe level of common windows (lower is better)
decibels relative to peak-60-40-20020-13.3-31.5-42.4-58.1rectangularHannHammingBlackman
Source: Computed with numpy: 64-point windows, zero-padded to 65536, peak sidelobe measured after the first null

The rectangular window's sidelobes sit only 13.3 dB down, so a strong tone leaks enough to bury a weak one 20 dB below it anywhere in the spectrum. Blackman pushes them to 58 dB down, a factor of over 800 in amplitude.

These figures match the reference table in Harris's 1978 paper on windows for harmonic analysis, which is still the standard citation, but they are computed here rather than quoted, so you can reproduce them in four lines.

5. Nothing is free: the main lobe gets wider

Suppressing sidelobes costs resolution. The taper effectively shortens the window, and a shorter window has a wider main lobe.

WindowPeak sidelobeMain lobe widthScalloping loss
Rectangular-13.3 dB2 bins3.9 dB
Hann-31.5 dB4 bins1.4 dB
Hamming-42.4 dB4 bins1.7 dB
Blackman-58.1 dB6 bins1.1 dB

So the choice is a real trade, not a ranking. Two tones three bins apart are resolvable with a rectangular window and merged into one hump by Blackman. A weak tone next to a strong one is invisible under a rectangular window and plain under Blackman.

The last column is the third effect: a tone between bin centres reads low, by up to 3.9 dB unwindowed. If you are measuring amplitudes rather than just spotting peaks, that error is larger than most of the ones people worry about.

6. The zero-padding trap

Predict first

You have 1024 samples and your two tones fall into the same bin. You pad the array to 8192 with zeros and transform that instead. The plot now has eight times as many points and looks much smoother. Have you resolved the two tones?

The confusion is understandable, because the picture improves in a visible way. What improved is the sampling of the curve, not the curve. The only cure for insufficient resolution is a longer recording.

7. Getting time back: the short-time transform

One transform of a whole recording tells you what frequencies are present and never when. The fix is mechanical: cut the signal into short overlapping chunks, window each one, transform each one, and stack the results into an image. That is the short-time Fourier transform, and the image is a spectrogram.

from scipy import signal
f, t, Zxx = signal.stft(x, fs=48000, nperseg=1024, noverlap=768)

Overlap matters and is easy to skip. The window tapers samples near its edges to nearly zero, so without overlap those samples barely contribute to any frame, and a transient landing on a boundary can vanish. Advancing by a quarter or a half of the window length is the usual choice.

8. The trade you cannot design your way out of

Choosing the chunk length sets both resolutions at once, in opposite directions. A short window pins down when and blurs what; a long window does the reverse.

This is not an artefact of the algorithm. It is a theorem: the time spread and frequency spread of any signal obey

ΔtΔf14π\Delta t \cdot \Delta f \geq \frac{1}{4\pi}

the same inequality that appears in quantum mechanics as the position-momentum uncertainty principle, for the same mathematical reason.

In practice: Pick the window from the question. Musical pitch at 48 kHz wants 2048 samples or more, about 43 ms, buying roughly 23 Hz resolution. Locating drum hits wants 256 samples, about 5 ms, and accepts 190 Hz. A spectrogram that looks wrong is usually a spectrogram whose window was chosen by default.

9. Why spectra are always plotted in decibels

Spectra are plotted logarithmically because the interesting range is enormous. Between a loud passage and the noise floor of a decent recording there can be six orders of magnitude, and on a linear axis everything below the top few percent is a flat line on the bottom.

L=20log10 ⁣(AAref)L = 20 \log_{10}\!\left(\frac{A}{A_{\text{ref}}}\right)

A few conversions worth memorising: 6 dB is a factor of 2 in amplitude, 20 dB is a factor of 10, and 60 dB is a factor of 1000.

Gotcha: The factor is 20 for amplitude and 10 for power, because power goes as amplitude squared. Getting this wrong doubles or halves every figure you report, and it is the most common error in the field. If a colleague's numbers are exactly twice yours, this is why.

10. Five questions to ask of any spectrum

Before believing a feature you see in a spectrum, check whether the analysis put it there.

  1. Was a window applied? If not, every peak has sidelobes 13 dB down, and a small bump near a large peak is probably leakage.
  2. Is the feature narrower than the main lobe? Nothing real can be. If it is, you are looking at the interpolation from zero-padding.
  3. Does it move when you change the window length? Real components stay put. Artefacts of the analysis shift.
  4. Is the peak amplitude trustworthy? Not unless it sits on a bin centre or you have accounted for scalloping loss.
  5. Could it be an alias? A feature at a suspiciously arbitrary frequency may be something above Nyquist folded down, and no amount of spectral care will fix that after the fact.

Almost every misread spectrum comes from one of these five, and all five are checkable in a minute.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. Why does a pure sine tone produce a smeared spectrum when it falls between bin centres?
    • Because the DFT implicitly repeats the window, and a non-integer number of cycles creates a discontinuity at the wrap
    • Because floating-point rounding accumulates over the transform
    • Because the tone is not truly band-limited
    • Because the FFT is an approximation of the DFT
  2. You need to detect a weak tone 40 dB below a nearby strong one. Which window is the reasonable choice?
    • Rectangular, because it has the narrowest main lobe
    • Hann, because it is the standard default
    • Blackman, because its sidelobes are about 58 dB down
    • Any of them: window choice affects only amplitude accuracy
  3. Two tones sit in the same DFT bin. You zero-pad from 1024 to 8192 points. What happens?
    • The tones separate, since the transform is now eight times longer
    • The spectrum is interpolated more finely but the tones remain unresolved
    • The spectrum becomes invalid, since the padding adds a discontinuity
    • Resolution improves by a factor of the square root of eight
  4. You are analysing a 48 kHz recording and want to locate percussive hits precisely in time. What window length is appropriate?
    • 8192 samples, for the best frequency detail
    • The full recording in one transform
    • The length does not affect time resolution, only overlap does
    • Around 256 samples, accepting coarse frequency resolution
  5. A colleague reports a level of -40 dB where you computed -20 dB from the same data. What is the likely explanation?
    • They forgot to apply a window
    • They used a different FFT length
    • One of you used the power convention (10 log) and the other the amplitude convention (20 log)
    • They zero-padded and you did not

Related lessons

Math
intermediate

The Frequency Domain: Why Everything Is Sinusoids

The same signal can be written as a function of time or as a recipe of frequencies. This lesson explains why sinusoids in particular get that job, builds the discrete Fourier transform, and shows how the FFT turned a quadratic computation into one you can run on a million samples in a fraction of a second.

10 steps·~15 min
Math
intermediate

Convolution and Filters: Shaping a Signal

A filter is fully described by what it does to a single impulse, and applying it is a convolution. This lesson builds that idea, shows why the frequency domain turns convolution into plain multiplication, and works through the trade-offs that make real filters ring, lag, or cost more than they need to.

10 steps·~15 min
Math
intermediate

Sampling and Aliasing: The Rule You Cannot Break

Turning a continuous signal into numbers is safe only above a specific rate, and below it the damage is silent and permanent. This lesson derives the Nyquist limit, shows exactly where a too-high frequency reappears, and explains why the fix has to be analogue and has to happen before the converter.

10 steps·~15 min
Math
advanced

Newton's method and the interior point revolution

Second derivatives buy something gradients cannot: a step shaped by curvature, immune to conditioning, converging quadratically. This lesson builds Newton's method, then layers it on a log barrier to get interior point methods, the machinery that made large constrained problems solvable with a certificate rather than a hope.

13 steps·~20 min