---
title: Sampling and the FFT
heading: What frequencies are in this signal?
eyebrow: A4 · Lesson 50 · Sampling and the FFT
xp: 40
---

::: hook
A recording of a motor's vibration looks like noise in time. Its spectrum shows a sharp peak at the shaft speed and another at twice that, which says exactly which part is out of balance. The fast Fourier transform turns samples in time into amplitudes at frequencies, and NumPy does it in one call. Reading the result correctly takes three ideas: which frequencies sampling can represent, which frequency each output bin stands for, and how to turn a bin's value into an amplitude.
:::

::: predict
## A 7 kHz tone is sampled at 10 kHz. What frequency do the samples look like?

- [ ] 7 kHz
- [ ] 17 kHz
- [x] 3 kHz
- [ ] 5 kHz

::: reveal
3 kHz. Sampling at 10 kHz can only represent frequencies up to 5 kHz (the **Nyquist frequency**, half the sample rate). A 7 kHz tone produces exactly the same samples as a 3 kHz one, $10 - 7 = 3$ kHz: it **aliases**. That's why every ADC has a low-pass filter in front of it.
:::
:::

::: nameit
## Sampling and aliasing

Sampling at rate $f_s$ captures frequencies from 0 up to $f_s/2$. A tone at frequency $f$ shows up at its **alias**:

$$f_{\text{alias}} = |f - k f_s| \quad\text{with } k \text{ the whole number that brings it into } [0, f_s/2]$$

In code: `fa = abs(f - fs * round(f / fs))`.

## The FFT of real samples

For $N$ samples taken at $f_s$:

```
X = np.fft.rfft(x)                   # N//2 + 1 complex values
f = np.fft.rfftfreq(N, d=1/fs)       # the frequency of each bin
```

- Bin $k$ stands for the frequency $k f_s / N$. The spacing $f_s/N = 1/T$ (one over the record length) is the **frequency resolution**: to tell apart tones 1 Hz apart, record for at least about a second.
- A sine of amplitude $A$ that falls exactly on bin $k$ gives $|X_k| = AN/2$. So the amplitude spectrum is `2 * np.abs(X) / N`, except at DC (bin 0), where it's `np.abs(X[0]) / N`.
- The FFT computes the DFT in $O(N\log N)$ operations instead of $O(N^2)$ (lesson 24).

## Leakage and windows

If a tone doesn't complete a whole number of cycles in the record, its energy smears into neighboring bins: **leakage**. Multiplying the samples by a smooth **window** such as `np.hanning(N)` before the FFT confines the smear to a few bins, at the cost of slightly wider peaks. A10 explains why.

## Finding peaks

The strongest tone is at `f[np.argmax(np.abs(X[1:])) + 1]` (skipping DC). For several tones, look for bins larger than both neighbors and above a threshold.
:::

::: example
## A signal is $\sin(2\pi \cdot 1000t) + 0.3\sin(2\pi \cdot 3000t)$, sampled at 8 kHz for 800 samples. What does the FFT show?

::: solution
1. **Take the FFT and scale it to amplitudes.** Multiply each magnitude by $2/N$.

```
import numpy as np
fs, N = 8000, 800
t = np.arange(N) / fs
x = np.sin(2 * np.pi * 1000 * t) + 0.3 * np.sin(2 * np.pi * 3000 * t)
A = 2 * np.abs(np.fft.rfft(x)) / N
f = np.fft.rfftfreq(N, 1 / fs)
print(f[A > 0.1], A[A > 0.1])        # [1000. 3000.] [1.  0.3]
```

2. **The bin spacing.**
   $$\begin{aligned} \Delta f &= \frac{8000}{800}\ \text{Hz} \\ &= 10\ \text{Hz} \end{aligned}$$
   so both tones land exactly on bins.
3. **Read the peaks.** The amplitudes come back as 1 and 0.3, at 1000 and 3000 Hz.

**Answer:** two clean peaks, an amplitude of 1 at 1000 Hz and 0.3 at 3000 Hz.
:::
:::

::: example
## A 12.3 kHz interference tone reaches an ADC sampling at 20 kHz without a filter. Where does it appear?

::: solution
1. **Find the nearest multiple of the sample rate.** $12.3/20 = 0.615$ rounds to 1.
2. **The alias frequency.**
   $$\begin{aligned} f_a &= |12.3 - 20|\ \text{kHz} \\ &= 7.7\ \text{kHz} \end{aligned}$$
3. **What it means.** It shows up at 7.7 kHz, inside the band, indistinguishable from a real 7.7 kHz signal.
4. **The fix.** After sampling, nothing can remove it; only an anti-alias filter before the ADC can.

**Answer:** the tone appears at 7.7 kHz.
:::
:::

::: check
kind: python
given: f = 3000 | 7000 | 12300 | 26000 | 45000; fs = 10000 | 20000 | 48000

## Write `alias(f, fs)` returning the apparent frequency of a tone `f` sampled at `fs`, in the range 0 to `fs/2`. Set `fa = alias(f, fs)` for `f` = {f} Hz and `fs` = {fs} Hz.

```python starter
def alias(f, fs):
    return f

fa = alias(f, fs)
print(fa)
```

```python solution
def alias(f, fs):
    return abs(f - fs * round(f / fs))

fa = alias(f, fs)
print(fa)
```

```python tests
assert alias(7000, 10000) == 3000, "alias(7000, 10000) should be 3000."
assert alias(3000, 10000) == 3000, "Below Nyquist, a tone stays where it is."
assert alias(26000, 10000) == 4000, "alias(26000, 10000) should be 4000: 26 kHz is 4 kHz away from 30 kHz."
assert abs(fa - abs(f - fs * round(f / fs))) < 1e-9, "fa doesn't match."
```
:::

::: check
kind: python
given: f1 = 400 | 600 | 1000; f2 = 1500 | 2200 | 3100; a2 = 0.2 | 0.5

## The starter samples two tones at 8 kHz for 1600 samples. Set `A` to the amplitude spectrum (`2 * |X| / N`), `f` to the bin frequencies, and `peaks` to the sorted frequencies of the bins with amplitude above 0.1.

```python starter
import numpy as np
fs, N = 8000, 1600
t = np.arange(N) / fs
x = np.sin(2 * np.pi * f1 * t) + a2 * np.cos(2 * np.pi * f2 * t)
A = f = None
peaks = []
print(peaks)
```

```python solution
import numpy as np
fs, N = 8000, 1600
t = np.arange(N) / fs
x = np.sin(2 * np.pi * f1 * t) + a2 * np.cos(2 * np.pi * f2 * t)
A = 2 * np.abs(np.fft.rfft(x)) / N
f = np.fft.rfftfreq(N, 1 / fs)
peaks = sorted(f[A > 0.1])
print(peaks)
```

```python tests
import numpy as np
assert A is not None and len(A) == 801, "np.fft.rfft of 1600 samples gives 801 bins."
assert list(map(float, peaks)) == [float(f1), float(f2)], f"The peaks should be at {f1} and {f2} Hz."
k2 = int(round(f2 * 1600 / 8000))
assert abs(A[k2] - a2) < 1e-9, "The second tone's amplitude should come back as a2: scale |X| by 2/N."
```
:::

::: check
kind: python
given: df = 0.5 | 2 | 10; fs = 1000 | 8000

## Two tones are `df` = {df} Hz apart. With sample rate `fs` = {fs} Hz, set `N` to the smallest number of samples whose bin spacing is at most `df`, and `T` to the record length in seconds.

```python starter
import math
N = 0
T = 0
print(N, T)
```

```python solution
import math
N = math.ceil(fs / df)
T = N / fs
print(N, T)
```

```python tests
import math
assert fs / N <= df and (N == 1 or fs / (N - 1) > df), "Bin spacing is fs/N: the smallest N with fs/N ≤ df."
assert abs(T - N / fs) < 1e-12, "T is N/fs."
```
:::

::: check
kind: python
given: A1 = 1 | 2.5; dc = 0 | 0.4 | 1.2; k1 = 20 | 37

## The starter makes `x`: a DC level plus a sine of amplitude `A1` landing exactly on bin `k1`. From `np.fft.rfft(x)`, set `dc_est` and `amp_est`.

```python starter
import numpy as np
N = 512
n = np.arange(N)
x = dc + A1 * np.sin(2 * np.pi * k1 * n / N)
dc_est = amp_est = 0
print(dc_est, amp_est)
```

```python solution
import numpy as np
N = 512
n = np.arange(N)
x = dc + A1 * np.sin(2 * np.pi * k1 * n / N)
X = np.fft.rfft(x)
dc_est = np.abs(X[0]) / N
amp_est = 2 * np.abs(X[k1]) / N
print(dc_est, amp_est)
```

```python tests
assert abs(dc_est - dc) < 1e-9, "The DC level is |X[0]|/N, without the factor of 2."
assert abs(amp_est - A1) < 1e-9, "A sine's amplitude is 2|X[k]|/N."
```
:::

::: check
kind: python
given: kb = 50.3 | 50.5 | 80.25; A = 1 | 2

## The starter makes `N` = 1000 samples of a sine of amplitude {A} whose frequency sits at bin {kb}, between bins. Set `amp_rect` to the largest value of `2 * abs(np.fft.rfft(x)) / N`, and `amp_hann` to the same for `x * np.hanning(N)`, divided also by the Hann window's coherent gain (its mean). Then set `loss_rect` and `loss_hann` to how far each falls below {A}, in dB.

```python starter
import numpy as np
N = 1000
n = np.arange(N)
x = A * np.sin(2 * np.pi * kb * n / N)
amp_rect = A
amp_hann = A
loss_rect = loss_hann = 0
print(amp_rect, amp_hann)
```

```python solution
import numpy as np
N = 1000
n = np.arange(N)
x = A * np.sin(2 * np.pi * kb * n / N)
amp_rect = np.max(2 * np.abs(np.fft.rfft(x)) / N)
w = np.hanning(N)
amp_hann = np.max(2 * np.abs(np.fft.rfft(x * w)) / N) / w.mean()
loss_rect = 20 * np.log10(A / amp_rect)
loss_hann = 20 * np.log10(A / amp_hann)
print(amp_rect, amp_hann, loss_rect, loss_hann)
```

```python tests
import numpy as np
N = 1000
n = np.arange(N)
xx = A * np.sin(2 * np.pi * kb * n / N)
ar = np.max(2 * np.abs(np.fft.rfft(xx)) / N)
w = np.hanning(N)
ah = np.max(2 * np.abs(np.fft.rfft(xx * w)) / N) / w.mean()
assert abs(amp_rect - ar) < 1e-9 * A and abs(amp_hann - ah) < 1e-9 * A, "Take the largest of 2|X|/N, and for Hann divide by the window's mean as well."
assert abs(loss_rect - 20 * np.log10(A / ar)) < 1e-9 and abs(loss_hann - 20 * np.log10(A / ah)) < 1e-9, "Each loss is 20 log10(A / amplitude)."
assert loss_hann < loss_rect, "The Hann window should lose less than the rectangular one between bins."
```

::: right
Right. Between bins a tone's energy splits across neighbors, and the plain FFT reads it low, by up to 3.9 dB halfway between bins. The Hann window's wider, flatter peak cuts that scalloping loss to 1.4 dB at worst.
:::
:::

::: check
given: fs = 8000 | 16000; N = 1000 | 2000 | 4000; f = 400 | 1000 | 2500 Hz
answer: f*N/fs
tolerance: 0.01

## A {f} tone is sampled at {fs} samples per second for {N} samples. Which FFT bin index $k$ (counting from 0) holds it exactly?

::: right
Right. Bin $k$ is at $k f_s/N$, so the tone is at $k = f N/f_s$ = {answer}.
:::

::: misses
- [f*fs/N] That's upside down. The bin spacing is $f_s/N$, so divide the frequency by it.
- [f/fs] That's the frequency as a fraction of the sample rate. Multiply by $N$ to count bins.
- [any] Not yet. Divide {f} by the bin spacing $f_s/N$.
:::
:::

::: explain
## Why does every ADC need a low-pass filter in front of it?

::: model
Once a signal is sampled, a tone above half the sampling rate produces exactly the same samples as a tone below it, its alias, so the two can't be told apart or separated afterwards. Any noise or interference above the Nyquist frequency would fold down into the band you care about and look like real signal. The only cure is to remove those frequencies before sampling, with an analog low-pass filter.
:::
:::

::: practice

::: check
kind: python
given: fs = 32000 | 40000 | 44100 | 48000 | 50000

## Set `nyq` to the Nyquist frequency for `fs` = {fs} Hz, and `fa` to where a 30 kHz tone appears.

```python starter
nyq = fa = 0
print(nyq, fa)
```

```python solution
nyq = fs / 2
fa = abs(30000 - fs * round(30000 / fs))
print(nyq, fa)
```

```python tests
assert abs(nyq - fs / 2) < 1e-9, "Nyquist is fs/2."
assert abs(fa - abs(30000 - fs)) < 1e-9, "30 kHz folds to fs − 30 kHz."
```
:::

::: check
kind: python
given: fs = 1000 | 4000; N = 200 | 500

## Set `f` to `np.fft.rfftfreq(N, 1/fs)` and `step` to its bin spacing.

```python starter
import numpy as np
f = None
step = 0
print(step)
```

```python solution
import numpy as np
f = np.fft.rfftfreq(N, 1 / fs)
step = f[1] - f[0]
print(step)
```

```python tests
assert abs(step - fs / N) < 1e-9, "The bin spacing is fs/N."
```
:::
:::
