---
title: Measuring spectra with the FFT
heading: What an FFT analyzer actually shows you
eyebrow: A10 · Lesson 16 · The FFT in practice
xp: 50
---

::: hook
Press the FFT button on an oscilloscope and a spectrum appears: but it's not the Fourier transform from the last few lessons. It's computed from a finite record of samples, so it can only show frequencies on a grid, it smears a tone that falls between grid points, and its heights depend on how you scale it. Reading such a spectrum correctly, and computing one yourself with NumPy, means knowing three things: bin spacing, amplitude scaling, and leakage with the windows that tame it.
:::

::: play
- A 1 V tone near 1 kHz is analyzed from a 4 ms record with a rectangular window. The spectrum is in decibels.
- Set the tone to exactly 1 kHz, then nudge it. As soon as it falls between the analyzer's grid points, energy spreads into a wide skirt.
- That spreading is leakage. How far down is the skirt several bins away?
:::
:::

```sim plot
view: spectrum
x: t = 0..4m s
y: v = -1.2..1.2 V
samples: 1024
freq: f = 0..4k Hz
scale: db
slider: f0 = 900..1100 step 5 = 1000 Hz
plot: sin(2*pi*f0*t) | label: tone
marker: f = f0 | label: true frequency
readout: bin spacing, Hz = 1/0.004 | digits: 4
readout: tone position, in bins = f0*0.004 | digits: 4
```

::: predict
## You sample at 8 kHz and take a 1024-point FFT. How far apart are the frequencies it can show?

- [ ] 8 kHz
- [ ] 1 Hz
- [x] 7.8 Hz
- [ ] 4 kHz

::: reveal
7.8 Hz: $\frac{f_s}{N} = \frac{8000}{1024}$. The bins are spaced by one over the record length, $\frac{1}{T} = \frac{1}{128\text{ ms}}$. A longer record gives finer resolution; a higher sample rate only extends the range, up to $f_s/2$.
:::
:::

::: nameit
## Bins

An $N$-point FFT of samples taken at $f_s$ gives values at frequencies

$$f_k = k\frac{f_s}{N}, \qquad k = 0, 1, \ldots, \frac{N}{2}$$

The spacing $\Delta f = \frac{f_s}{N} = \frac{1}{T}$ is set by the record length $T$. The highest frequency is $f_s/2$, the Nyquist frequency. In NumPy, `np.fft.rfft(x)` returns the $\frac{N}{2} + 1$ values and `np.fft.rfftfreq(N, 1/fs)` their frequencies.

## Scaling

A sine of amplitude $A$ that lands exactly on a bin gives $|X_k| = \frac{AN}{2}$, so the amplitude spectrum is $\frac{2|X_k|}{N}$. (The DC bin and the Nyquist bin aren't doubled.)

## Leakage

A finite record is the infinite signal multiplied by a rectangular window, so the spectrum is convolved with a sinc. A tone exactly on a bin falls on the sinc's peak and lands on the other bins' zeros. A tone between bins spreads into all of them: its peak drops (by up to 3.9 dB, the "picket fence" loss) and its skirt falls only slowly, about $-32$ dB twenty bins away.

## Windows

Multiplying the record by a smooth taper, such as the **Hann** window $w_n = \frac{1}{2}(1 - \cos\frac{2\pi n}{N})$, kills the abrupt edges. The skirt drops to about $-86$ dB twenty bins away, and the worst peak loss to 1.4 dB, at the price of a main lobe twice as wide. Normalize by $\sum w_n$ instead of $N$ to keep amplitudes right.
:::

::: example
## A 3 V, 1 kHz tone is sampled at 8 kHz for 1024 points. Where is it in the FFT, and how big?

::: solution
1. **Find the bin.**
   $$\begin{aligned} k &= \frac{1000 \times 1024}{8000} \\ &= 128 \end{aligned}$$
   exactly.
2. **Its magnitude.**
   $$\frac{3 \times 1024}{2} = 1536$$
3. **Recover the amplitude.**
   $$\frac{2 \times 1536}{1024} = 3\ \text{V}$$

**Answer:** it lands exactly in bin 128 with magnitude 1536, which scales back to 3 V.
:::
:::

::: example
## The tone moves to 1003.9 Hz, half a bin off. What do the rectangular and Hann spectra show?

::: solution
1. **The rectangular window.** The peak reads 1.92 V (down 3.9 dB), and the skirt 20 bins away is only 32 dB down.
2. **The Hann window.** Normalized by $\sum w$, the peak reads 2.55 V (down 1.4 dB), and the skirt 20 bins away is 86 dB down.
3. **Compare.** For measuring a weak tone near a strong one, the window makes the difference.

**Answer:** the rectangular window reads 1.92 V with its skirt only 32 dB down 20 bins away; Hann reads 2.55 V with the skirt 86 dB down.
:::
:::

::: check
given: fs = 8000 | 48000; N = 1024 | 4096
answer: fs/N
unit: Hz
tolerance: 0.5%

## What is the bin spacing of an {N}-point FFT at a sample rate of {fs} Hz?

::: right
Right. $\frac{f_s}{N}$ = {answer}.
:::

::: misses
- [N/fs] Upside down.
- [fs/(2*N)] That's half a bin.
- [any] Not yet. $\Delta f = f_s/N$.
:::
:::

::: check
given: fs = 8000 | 10000; N = 1024 | 2048; f0 = 1000 | 2500
answer: f0*N/fs
tolerance: 0.5%

## At which bin index does a tone at {f0} Hz fall, for an {N}-point FFT at {fs} Hz?

::: right
Right. $k = \frac{f_0N}{f_s}$ = {answer}.
:::

::: misses
- [f0*fs/N] Divide by the bin spacing $f_s/N$.
- [any] Not yet. $f_0$ over $\Delta f$.
:::
:::

::: check
given: X = 1536 | 512; N = 1024 | 4096
answer: 2*X/N
unit: V
tolerance: 0.5%

## A tone sits exactly on a bin of an {N}-point FFT, with $|X_k|$ = {X}. What is its amplitude?

::: right
Right. $\frac{2|X_k|}{N}$ = {answer}.
:::

::: misses
- [X/N] The tone's energy splits between positive and negative frequencies: double it.
- [any] Not yet. $A = 2|X_k|/N$.
:::
:::

::: check
given: df = 2 | 0.5 | 10
answer: 1/df
unit: s
tolerance: 0.5%

## How long a record do you need for a bin spacing of {df} Hz?

::: right
Right. $T = \frac{1}{\Delta f}$ = {answer}.
:::

::: misses
- [df] Finer resolution needs a longer record: $T = 1/\Delta f$.
- [any] Not yet. $\Delta f = 1/T$.
:::
:::

::: check
given: fs = 8000 | 22050 | 44100 | 48000 | 96000 | 192000
answer: fs/2
unit: Hz

## What is the highest frequency an FFT of data sampled at {fs} Hz can show?

::: right
Right. The Nyquist frequency, $f_s/2$ = {answer}.
:::

::: misses
- [fs] Only up to half the sample rate.
- [any] Not yet. $f_s/2$.
:::
:::

::: check
kind: python

## Write `spectrum(x, fs)` returning `(freqs, amps)`: the frequencies from `np.fft.rfftfreq` and the amplitudes $\frac{2|X_k|}{N}$ from `np.fft.rfft`. Then a tone's amplitude and frequency can be read off the peak.

```python starter
import numpy as np

def spectrum(x, fs):
    N = len(x)
    return np.zeros(N // 2 + 1), np.zeros(N // 2 + 1)

fs, N = 8000, 1024
t = np.arange(N) / fs
f, a = spectrum(3 * np.sin(2 * np.pi * 1000 * t), fs)
print(f[np.argmax(a)], a.max())
```

```python solution
import numpy as np

def spectrum(x, fs):
    N = len(x)
    return np.fft.rfftfreq(N, 1 / fs), 2 * np.abs(np.fft.rfft(x)) / N

fs, N = 8000, 1024
t = np.arange(N) / fs
f, a = spectrum(3 * np.sin(2 * np.pi * 1000 * t), fs)
print(f[np.argmax(a)], a.max())
```

```python tests
import numpy as np
fs, N = 8000, 1024
t = np.arange(N) / fs
f, a = spectrum(3 * np.sin(2 * np.pi * 1000 * t) + 0.5 * np.sin(2 * np.pi * 2500 * t), fs)
assert len(f) == N // 2 + 1 and np.isclose(f[1], fs / N), "Frequencies should run from 0 to fs/2 in steps of fs/N."
k = np.argmax(a)
assert np.isclose(f[k], 1000) and np.isclose(a[k], 3), f"The 1 kHz tone should read 3 V; got {a[k]:.3f} V at {f[k]:.1f} Hz."
assert np.isclose(a[np.argmin(np.abs(f - 2500))], 0.5), "The 2.5 kHz tone should read 0.5 V."
```

::: right
Right. On-bin tones read their amplitudes exactly. Try a tone at 1003.9 Hz to see the picket-fence loss.
:::
:::

::: check
kind: python

## Write `hann_spectrum(x, fs)`: multiply by `np.hanning(len(x))` before the FFT and normalize by `2/np.sum(w)` instead of `2/N`. The test compares leakage far from a tone that falls between bins.

```python starter
import numpy as np

def hann_spectrum(x, fs):
    N = len(x)
    return np.fft.rfftfreq(N, 1 / fs), 2 * np.abs(np.fft.rfft(x)) / N

fs, N = 8000, 1024
t = np.arange(N) / fs
f, a = hann_spectrum(3 * np.sin(2 * np.pi * 1003.9 * t), fs)
print(a.max())
```

```python solution
import numpy as np

def hann_spectrum(x, fs):
    N = len(x)
    w = np.hanning(N)
    return np.fft.rfftfreq(N, 1 / fs), 2 * np.abs(np.fft.rfft(x * w)) / np.sum(w)

fs, N = 8000, 1024
t = np.arange(N) / fs
f, a = hann_spectrum(3 * np.sin(2 * np.pi * 1003.9 * t), fs)
print(a.max())
```

```python tests
import numpy as np
fs, N = 8000, 1024
t = np.arange(N) / fs
f, a = hann_spectrum(3 * np.sin(2 * np.pi * 1003.9 * t), fs)
k = np.argmax(a)
assert 2.4 < a[k] < 3.0, f"With Hann the peak should read about 2.55 V; got {a[k]:.2f}. Normalize by the window's sum."
assert 20 * np.log10(a[k + 20] / a[k]) < -70, "Twenty bins away, Hann's leakage should be more than 70 dB down."
g, b = hann_spectrum(3 * np.sin(2 * np.pi * 1000 * t), fs)
assert abs(b.max() - 3) < 0.01, "An on-bin tone should still read 3 V."
```

::: right
Right. The skirt falls from about −32 dB to −86 dB twenty bins away, and the worst-case peak error shrinks too.
:::
:::

::: explain
## Why does a tone that falls between FFT bins spread into all the other bins?

::: model
The FFT treats the finite record as one period of a repeating signal. If the tone doesn't complete a whole number of cycles in the record, the repeated version has a jump where the end meets the start, and a jump contains every frequency. Equivalently, the record is the true signal times a rectangular window, so its spectrum is the tone's line convolved with the window's sinc. On a bin, the other bins sit on the sinc's zeros; off a bin, they sample its side lobes. A tapered window removes the jump and lowers the side lobes.
:::
:::

::: practice

::: check
given: fs = 1000 | 20000; N = 500 | 2000
answer: N/fs
unit: s
tolerance: 0.5%

## How long is the record of an {N}-point FFT at {fs} Hz?

::: misses
- [fs/N] That's the bin spacing.
- [any] $T = N/f_s$.
:::
:::

::: check
given: k = 50 | 200; fs = 8000 | 48000; N = 1024 | 8192
answer: k*fs/N
unit: Hz
tolerance: 0.5%

## What frequency does bin {k} of an {N}-point FFT at {fs} Hz represent?

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

::: check
given: d = 1 | 2 | 4 | 5 | 10 | 20
answer: 2/d
unit: s
tolerance: 0.5%

## With a Hann window, whose main lobe is twice as wide, about how long a record separates two tones {d} Hz apart? (Use $T \approx 2/\Delta f$.)

::: misses
- [1/d] Hann's wider main lobe needs about twice the record.
- [any] $2/\Delta f$.
:::
:::
:::
