---
title: Windows and spectral leakage
heading: Why a pure tone smears across the DFT, and how windows tame it
eyebrow: C9 · Lesson 25 · Windows and spectral leakage
xp: 40
---

::: hook
Take the DFT of a pure tone and you'd expect one spike. You get one spike only if the tone fits a whole number of cycles in the record. Otherwise its energy leaks into every bin, and a weak tone a few bins away disappears under the leakage. The fix is to fade the record in and out before transforming it. Choosing that fade, the window, is a trade between seeing weak signals, separating close ones, and measuring amplitudes accurately.
:::

::: play
- The curve is the spectrum of one tone through a window, in dB, against frequency in bins; the stems are where the DFT samples it.
- Set the offset to 0: the tone sits on a bin, and with the rectangular window (w = 0) every other stem is at a null. Move it to 0.5 and energy appears in every bin.
- Switch to the Hann window (w = 1). The peak is wider, but the leakage far from the peak drops from about −30 dB to below −70 dB at 10 bins.
:::

```sim plot
view: graph
x: k = -12..12
y: L = -90..5 dB
slider: d = 0..1 step 0.05 = 0.5
slider: w = 0..1 step 1 = 0
plot: 20*log(abs((sin(pi*(k - d)) + 0.000000000001)/(pi*(k - d) + 0.000000000001) + w*0.5*((sin(pi*(k - d - 1)) + 0.000000000001)/(pi*(k - d - 1) + 0.000000000001) + (sin(pi*(k - d + 1)) + 0.000000000001)/(pi*(k - d + 1) + 0.000000000001))) + 0.00001) | dashed | samples: 997 | label: window spectrum
plot: 20*log(abs((sin(pi*(k - d)) + 0.000000000001)/(pi*(k - d) + 0.000000000001) + w*0.5*((sin(pi*(k - d - 1)) + 0.000000000001)/(pi*(k - d - 1) + 0.000000000001) + (sin(pi*(k - d + 1)) + 0.000000000001)/(pi*(k - d + 1) + 0.000000000001))) + 0.00001) | stems | label: DFT bins
readout: bin 0, dB = 20*log(abs((sin(pi*(-d)) + 0.000000000001)/(pi*(-d) + 0.000000000001) + w*0.5*((sin(pi*(-d - 1)) + 0.000000000001)/(pi*(-d - 1) + 0.000000000001) + (sin(pi*(-d + 1)) + 0.000000000001)/(pi*(-d + 1) + 0.000000000001)))) | digits: 3
```

::: predict
## With the rectangular window, a tone falls exactly halfway between two bins. How far below its true level does the largest bin read?

- [ ] 0 dB
- [ ] 1.4 dB
- [x] 3.9 dB
- [ ] 13.3 dB

::: reveal
3.9 dB: the bin sits half a bin from the peak of the window's spectrum, where $\operatorname{sinc}(0.5) = 2/\pi$ = 0.637. This **scalloping loss** makes the same tone read up to 36% low depending on its exact frequency. With the Hann window it's only 1.4 dB.
:::
:::

::: nameit
## Where leakage comes from

An N-sample record is the signal multiplied by a **window** that is 1 for N samples and 0 elsewhere. Multiplying in time convolves in frequency, so every tone's line is replaced by the window's spectrum, centered on the tone. For the rectangular window that's a sinc: a main lobe 2 bins wide and side lobes that fall only as 1/(bin distance). The DFT samples this at the bins. If the tone is exactly on a bin, the samples land on the nulls; otherwise they catch the side lobes, and the tone leaks into every bin.

## Windows

A window tapers the record smoothly to zero at both ends, so the periodic extension the DFT assumes has no jump. Smoother edges mean lower side lobes, but a wider main lobe.

| Window | Main lobe (null to null) | Highest side lobe | Scalloping loss | Noise bandwidth | Coherent gain |
|---|---|---|---|---|---|
| rectangular | 2 bins | −13.3 dB | 3.92 dB | 1.00 bin | 1 |
| Hann | 4 bins | −31.5 dB | 1.42 dB | 1.50 bins | 0.5 |
| Hamming | 4 bins | −42.7 dB | 1.75 dB | 1.36 bins | 0.54 |
| Blackman | 6 bins | −58.1 dB | 1.10 dB | 1.73 bins | 0.42 |

The Hann window is $w[n] = \tfrac12(1 - \cos(2\pi n/N))$. Its spectrum is three shifted sincs, $\tfrac12\operatorname{sinc}(b) + \tfrac14\operatorname{sinc}(b - 1) + \tfrac14\operatorname{sinc}(b + 1)$, whose side lobes partly cancel.

## Choosing one

- **Resolution**: two tones closer than about one main-lobe half-width merge. The rectangular window resolves the closest tones of equal size.
- **Dynamic range**: to see a weak tone near a strong one, the strong tone's leakage there must be below the weak one. Hann, Hamming or Blackman.
- **Amplitude**: a flat-top window has almost no scalloping loss, at the cost of a very wide main lobe.
- **Noise**: a window's noise bandwidth is how many bins' worth of noise each bin collects. Divide a bin's power by it to get a noise density.

A windowed tone's bin height is reduced by the window's **coherent gain**, the average of the window: an on-bin tone of amplitude A reads $NA\cdot CG/2$, so divide by the coherent gain to measure amplitudes.

## The spectrogram

Sliding a window along a long signal and taking a DFT at each position gives a **short-time Fourier transform**, drawn as a spectrogram. A longer window resolves frequency better and time worse; there is no window that does both.
:::

::: example
## A 1010 Hz tone is analyzed with a 256-point DFT at 8 kHz. Where does it fall, and how much does the nearest bin lose with no window?

::: solution
1. **Bin spacing.**
   $$8000/256 = 31.25\ \text{Hz}$$
2. **Where the tone falls.**
   $$1010/31.25 = 32.32\ \text{bins}$$
3. **Loss at the nearest bin.** Bin 32 is 0.32 bins off:
   $$\operatorname{sinc}(0.32) = 0.839$$
   which is 1.5 dB low.
4. **Leakage.** A bin 10 away reads only about 32 dB below the peak, so the leakage spreads far across the spectrum.

**Answer:** the tone falls at bin 32.32, and the nearest bin, 32, reads 0.839 of the full height, 1.5 dB low.
:::
:::

::: example
## A strong tone and a tone 50 dB weaker are 10 bins apart. Which window shows the weak one?

::: solution
1. **Rectangular window.** Its spectrum, 10 bins from its peak, is as high as −29.5 dB, depending on where the tone falls between bins.
2. **The weak tone under it.** That's 20 dB above the weak tone, which vanishes.
3. **Hann window.** Its spectrum there is below −68.5 dB, so the weak tone stands 18 dB clear.
4. **Main lobe.** The Hann window's wider main lobe costs nothing at this spacing.

**Answer:** the Hann window shows the weak tone, 18 dB clear; with the rectangular window it vanishes.
:::
:::

::: example
## A 1024-point DFT sees an on-bin tone of amplitude 2 V. What does its bin read with the rectangular window and with the Hann window?

::: solution
1. **Rectangular.**
   $$\begin{aligned} NA/2 &= 1024 \times 2/2 \\ &= 1024 \end{aligned}$$
2. **Hann.** The coherent gain is 0.5, so the bin reads 512.
3. **Recover the amplitude.** To recover 2 V from the Hann bin, compute
   $$2 \times 512/(1024 \times 0.5)$$
4. **The trap.** Forgetting the coherent gain reads the amplitude 6 dB low.

**Answer:** the bin reads 1024 with the rectangular window and 512 with the Hann window.
:::
:::

::: check
kind: parts
given: d = 0.1 | 0.25 | 0.5

## A tone falls {d} of a bin away from the nearest bin.

::: part
answer: 20*log(sin(pi*d)/(pi*d))
unit: dB
tolerance: 0.5%

### How far below its true level does that bin read with the rectangular window?

::: misses
- [any] $20\log_{10}\operatorname{sinc}(d)$.
:::
:::

::: part
answer: 20*log(sin(pi*d)/(pi*d) + 0.5*(sin(pi*(d - 1))/(pi*(d - 1)) + sin(pi*(d + 1))/(pi*(d + 1))))
unit: dB
tolerance: 0.5%

### And with the Hann window?

::: misses
- [any] Use the three-sinc spectrum: $\operatorname{sinc}(d) + \tfrac12[\operatorname{sinc}(d - 1) + \operatorname{sinc}(d + 1)]$.
:::
:::
:::

::: check
kind: parts
given: fs = 8000 | 44100 | 1000000; N = 256 | 1024 | 4096

## An {N}-point DFT runs at {fs} Hz.

::: part
answer: fs/N
unit: Hz
tolerance: 0.5%

### About how close can two equal tones be and still be resolved with the rectangular window (one bin)?

::: misses
- [any] One bin: $f_s/N$.
:::
:::

::: part
answer: 2*fs/N
unit: Hz
tolerance: 0.5%

### And with the Hann window, whose main lobe is twice as wide?

::: misses
- [any] Two bins.
:::
:::
:::

::: check
kind: parts
given: N = 512 | 1024 | 4096; A = 0.5 | 1 | 3

## An on-bin tone of amplitude {A} goes into an {N}-point DFT.

::: part
answer: N*A/2
tolerance: 0.5%

### What does its bin read with the rectangular window?

::: misses
- [N*A] A real tone splits its height between the positive and negative frequency.
- [any] $NA/2$.
:::
:::

::: part
answer: N*A/4
tolerance: 0.5%

### And with the Hann window?

::: misses
- [any] Times the coherent gain, 0.5.
:::
:::
:::

::: check
kind: parts
given: fs = 48000 | 1000; N = 1024 | 8192; B = 1.36 | 1.5 | 1.73

## A window with a noise bandwidth of {B} bins is used for an {N}-point DFT at {fs} Hz.

::: part
answer: B*fs/N
unit: Hz
tolerance: 0.5%

### What noise bandwidth does each bin have, in hertz?

::: misses
- [fs/N] Multiply by the window's noise bandwidth in bins.
- [any] Bins × bin spacing.
:::
:::

::: part
answer: 10*log(B)
unit: dB
tolerance: 0.5%

### How much more noise power does a bin collect than with the rectangular window?

::: misses
- [any] $10\log_{10}$ of the ratio.
:::
:::
:::

::: check
kind: choice

## Which property of a window matters most for seeing a weak tone many bins away from a strong one?

- [ ] A narrow main lobe
- [x] Low side lobes far from the main lobe
- [ ] A small scalloping loss
- [ ] A coherent gain close to 1

::: misses
- [1] That matters for tones a bin or two apart; far away, it's the strong tone's leakage that hides the weak one.
- [3] Scalloping changes how a tone's own level reads, not how far its leakage spreads.
- [4] Coherent gain only scales every bin; it doesn't change the ratio between them.
:::
:::

::: check
kind: derivation
vars: f = 1000..1000000, N = 64..65536

## A record of N samples is taken at a rate f.

::: step
answer: f/N

### How far apart are the DFT bins?
:::

::: step
answer: N/f

### How long is the record?
:::

::: step
answer: 1

### What is the product of the two?
:::

::: right
Right. The frequency spacing is one over the record length, whatever the sample rate.
:::
:::

::: check
kind: python

## Write `tone_amplitude(x, window)`: estimate the amplitude of the single tone in x from its largest DFT bin (ignoring bin 0), where `window` is `'rect'` or `'hann'`. Apply the window, take `numpy.fft.rfft`, and correct for the coherent gain.

```python starter
import numpy as np

def tone_amplitude(x, window):
    return np.max(np.abs(np.fft.rfft(x)))
```

```python solution
import numpy as np

def tone_amplitude(x, window):
    x = np.asarray(x, dtype=float)
    n = len(x)
    w = np.ones(n) if window == 'rect' else 0.5 * (1 - np.cos(2 * np.pi * np.arange(n) / n))
    X = np.abs(np.fft.rfft(x * w))
    return 2 * np.max(X[1:]) / (n * np.mean(w))
```

```python tests
import numpy as np
n = np.arange(1024)
on = 2.0 * np.cos(2 * np.pi * 37 * n / 1024 + 0.4)
assert abs(tone_amplitude(on, 'rect') - 2.0) < 1e-9, f"An on-bin 2 V tone should read 2.0 with no window, got {tone_amplitude(on, 'rect')}."
assert abs(tone_amplitude(on, 'hann') - 2.0) < 1e-9, f"With the Hann window, divide by its coherent gain: 2.0, got {tone_amplitude(on, 'hann')}."
off = 1.5 * np.cos(2 * np.pi * 37.5 * n / 1024)
r, h = tone_amplitude(off, 'rect'), tone_amplitude(off, 'hann')
assert abs(r / 1.5 - 0.637) < 0.01, f"Half a bin off, the rectangular window reads 63.7% of 1.5 V; got {r:.3f}."
assert abs(h / 1.5 - 0.849) < 0.01, f"Half a bin off, the Hann window reads 84.9% of 1.5 V; got {h:.3f}."
```

::: right
Right. The same tone reads 64% or 85% of its true size half a bin off, depending on the window: scalloping loss in action.
:::
:::

::: explain
## Why does a tone that doesn't fit a whole number of cycles in the record leak into every DFT bin?

::: model
The DFT treats the record as one period of a periodic signal. If the tone completes a whole number of cycles, the repeated record joins smoothly and is exactly a sinusoid at a bin frequency, so it lands in one bin. If not, the repetition has a jump at every record boundary, and a jump needs energy at all frequencies. Equivalently, the record is the infinite tone multiplied by a rectangular window, which convolves the tone's line with the window's sinc-shaped spectrum; sampling that sinc anywhere but its nulls picks up the side lobes. A tapered window removes the jump, so its spectrum has much lower side lobes and the leakage falls off quickly away from the tone.
:::
:::

::: practice
::: check
given: d = 0.1 | 0.2 | 0.25 | 0.3 | 0.4 | 0.5
answer: 20*log(sin(pi*d)/(pi*d))
unit: dB
tolerance: 0.5%

## A tone {d} bin off, rectangular window. Scalloping loss?

::: misses
- [any] $20\log_{10}\operatorname{sinc}(d)$.
:::
:::

::: check
given: fs = 10000 | 96000; N = 2048 | 512
answer: fs/N
unit: Hz
tolerance: 0.5%

## Bin spacing of an {N}-point DFT at {fs} Hz?

::: misses
- [any] $f_s/N$.
:::
:::

::: check
given: N = 256 | 2048; A = 1 | 4
answer: N*A/4
tolerance: 0.5%

## An on-bin tone of amplitude {A}, Hann window, {N} points. Bin height?

::: misses
- [any] $NA\cdot 0.5/2$.
:::
:::
:::
