---
title: Sampling and the DFT
heading: From a continuous signal to a list of numbers, and back to a spectrum
eyebrow: A10 · Lesson 15 · Sampling and the DFT, previewed
xp: 50
---

::: hook
A computer can't store a continuous signal. It stores samples: the voltage measured thousands or millions of times a second. Between samples it knows nothing. Surprisingly, that's enough to rebuild the signal exactly, if you sample fast enough. Sample too slowly and a high frequency puts on a disguise: it shows up as a lower frequency that was never there. Once the signal is a list of numbers, the discrete Fourier transform finds its spectrum, and that's what runs inside every digital scope and spectrum analyzer.

::: play
- A sine at frequency $f$ is sampled at 1 kHz. The staircase holds each sample until the next one, the way a simple converter does. The dashed curve is the lowest-frequency sine that passes through the same samples.
- Start well below 500 Hz and raise $f$. What happens once $f$ passes 500 Hz? At 1 kHz?
- Find two different values of $f$ that give exactly the same samples.
:::
:::

```sim plot
view: graph
x: t = 0..20m s
y: v = -1.5..1.5 V
slider: f = 0..2000 step 25 = 100 Hz
plot: sin(2*pi*f*t) | samples: 3000 | color: ch3 | label: signal
plot: sin(2*pi*f*floor(t*1000 + 1e-9)/1000) | samples: 3000 | label: samples, held
plot: sin(2*pi*(f - 1000*round(f/1000))*t) | dashed | color: ch2 | samples: 3000 | label: alias
readout: alias frequency = abs(f - 1000*round(f/1000)) Hz
```

::: predict
## A 900 Hz tone is sampled at 1 kHz, with no filter first. What frequency does the sampled data seem to contain?

- [ ] 900 Hz
- [ ] 1900 Hz
- [x] 100 Hz
- [ ] 500 Hz

::: reveal
100 Hz. At 1 kHz, a 900 Hz sine advances 0.9 of a cycle between samples, which looks exactly like going back 0.1 of a cycle: a 100 Hz sine running backward. Once sampled, there's no way to tell them apart. That's **aliasing**, the same effect that makes wagon wheels in films seem to turn slowly or backward. The only cure is to remove frequencies above half the sample rate before sampling.
:::
:::

::: nameit
## Sampling

**Samples.** Measuring $x(t)$ every $T_s$ seconds gives the list $x[n] = x(nT_s)$, at a **sample rate** $f_s = 1/T_s$.

**The sampling theorem.** A signal whose frequencies all lie below $f_s/2$ can be rebuilt exactly from its samples. That limit, $f_s/2$, is the **Nyquist frequency**; equivalently, you must sample at more than twice the highest frequency present. CD audio samples at 44.1 kHz to cover hearing up to 20 kHz.

**Aliasing.** A frequency above $f_s/2$ isn't lost, it's disguised. Its samples match those of a lower frequency, the **alias**:

$$f_\text{alias} = |f - kf_s|$$

for the whole number $k$ that brings it into the range $0$ to $f_s/2$. Every frequency band folds back into that range. So every analog-to-digital converter is preceded by an **anti-aliasing filter**, a low-pass that removes what's above $f_s/2$ before it can masquerade as something else.

## The discrete Fourier transform

With $N$ samples, the **DFT** correlates the data with $N$ complex sinusoids, exactly like the Fourier series coefficients of lesson 2:

$$X[k] = \sum_{n=0}^{N-1} x[n]\,e^{-j2\pi kn/N}$$

- Bin $k$ corresponds to the frequency $kf_s/N$, so the bins are $f_s/N$ apart: one over the record's length (lesson 13's resolution limit).
- A tone that fits a whole number of cycles in the record lands in a single bin. One that doesn't spreads into its neighbors: **leakage**, which window functions reduce.
- Computed directly, the DFT takes about $N^2$ operations. The **fast Fourier transform** (FFT) gets the same answer in about $N\log_2N$: for a million samples, 20 million instead of a trillion. It's one of the most important algorithms in engineering.

Course C9 (signals and systems) and the DSP survey build on all of this.
:::

::: example
## Tones at 7, 13 and 23 kHz are sampled at 10 kHz. Where does each appear?

::: solution
1. **The rule.** Bring each tone into 0 to 5 kHz with $|f - kf_s|$.
2. **Fold each tone.** In kHz:
   $$\begin{aligned} |7 - 10| &= 3 \\ |13 - 10| &= 3 \\ |23 - 20| &= 3 \end{aligned}$$
3. **Compare.** All three land at 3 kHz and can't be told apart in the data.

**Answer:** all three appear at 3 kHz.
:::
:::

::: example
## You take a DFT of 1000 samples at 10 kHz. How far apart are the bins, where does a 1.25 kHz tone land, and how much work does the FFT save?

::: solution
1. **The bin spacing.**
   $$\frac{10\ \text{kHz}}{1000} = 10\ \text{Hz}$$
2. **The tone's bin.**
   $$\frac{1250\ \text{Hz}}{10\ \text{Hz}} = 125$$
3. **A direct DFT.** It takes about $1000^2 = 10^6$ operations.
4. **The FFT.** It takes about
   $$1000\log_21000 \approx 10{,}000$$
   a hundred times fewer.

**Answer:** the bins are 10 Hz apart, the tone lands in bin 125, and the FFT does about a hundred times less work.
:::
:::

::: example
## Telephone speech is limited to 3.4 kHz and sampled at 8 kHz. What is the minimum sampling rate, and why use more?

::: solution
1. **Nyquist's minimum.** It's twice the highest frequency:
   $$2 \times 3.4\ \text{kHz} = 6.8\ \text{kHz}$$
2. **The guard band.** Sampling at 8 kHz puts the first alias of a 3.4 kHz tone at
   $$8 - 3.4 = 4.6\ \text{kHz}$$
   1.2 kHz above the band.
3. **What the filter has to do.** The anti-aliasing filter only has to roll off between 3.4 and 4.6 kHz, which a practical filter can do, rather than from 3.4 kHz to 3.4 kHz, which no filter can.

**Answer:** the minimum is 6.8 kHz; sampling at 8 kHz leaves a 1.2 kHz guard band that a practical anti-aliasing filter can work in.
:::
:::

::: check
given: fmax = 3 | 4 | 15 | 20 | 100
answer: 2*fmax
unit: kHz
tolerance: 0.5%

## A signal has frequencies up to {fmax} kHz. What is the lowest sample rate that can capture it without aliasing?

::: right
Right. More than twice the highest frequency: {answer}.
:::

::: misses
- [fmax] Sampling at the highest frequency itself catches the same point on every cycle: the tone looks like DC.
- [any] Not yet. $f_s > 2f_\text{max}$.
:::
:::

::: check
given: fs = 8 | 10 | 48; r = 0.6 | 0.7 | 1.2 | 1.3; let f = fs*r
answer: abs(f - fs*round(f/fs))
unit: kHz
tolerance: 0.5%

## A {f} kHz tone is sampled at {fs} kHz with no anti-aliasing filter. At what frequency does it appear in the data?

::: right
Right. Shift it by the nearest multiple of {fs} kHz: $|\given{f} - k \cdot \given{fs}|$ = {answer}.
:::

::: misses
- [f] It's above $f_s/2$ = {fs}/2 kHz, so it can't appear as itself.
- [f - fs/2] Fold it around multiples of $f_s$, not $f_s/2$: the alias is $|f - kf_s|$.
- [any] Not yet. Find $|f - kf_s|$ for the whole number k that puts it between 0 and $f_s/2$.
:::
:::

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

## A DFT of {N} samples taken at {fs} Hz has bins how far apart?

::: right
Right. $f_s/N$ = {answer}, which is one over the record's length.
:::

::: misses
- [N/fs] That's the record's length in seconds. The bin spacing is its reciprocal.
- [fs/(2*N)] The bins are $f_s/N$ apart.
- [any] Not yet. Bin spacing $= f_s/N$.
:::
:::

::: check
kind: python
given: f0 = 50 | 120 | 230 | 310

## A sine wave at an unknown frequency has been sampled for you: `x` holds 1000 samples taken at 1000 Hz. Use `np.fft.rfft` to find its frequency, and set `f_peak` to it in hertz.

```python starter
import numpy as np

fs = 1000
n = np.arange(1000)
x = 0.8 * np.sin(2 * np.pi * f0 * n / fs + 0.3)

X = np.fft.rfft(x)
freqs = np.fft.rfftfreq(len(x), 1 / fs)
f_peak = 0   # replace: the frequency of the biggest bin
print(f_peak)
```

```python solution
import numpy as np

fs = 1000
n = np.arange(1000)
x = 0.8 * np.sin(2 * np.pi * f0 * n / fs + 0.3)

X = np.fft.rfft(x)
freqs = np.fft.rfftfreq(len(x), 1 / fs)
f_peak = freqs[np.argmax(np.abs(X))]
print(f_peak)
```

```python tests
assert abs(f_peak - f0) < 0.5, f"The tone is at {f0} Hz; your f_peak is {f_peak}."
```

::: right
Right. With a 1 s record the bins are 1 Hz apart, and a whole number of cycles puts the whole tone in one bin.
:::
:::

::: check
kind: choice

## Where does an anti-aliasing filter go, and why?

- [x] Before the converter: once a frequency has aliased, it can't be told apart from a real low one
- [ ] After the converter, as a digital filter
- [ ] Anywhere: filtering commutes with sampling
- [ ] It isn't needed if you sample fast enough for the signal you want

::: right
Right. Aliasing happens at the moment of sampling, so the unwanted frequencies have to be gone by then.
:::

::: misses
- [2] After sampling, an aliased tone looks exactly like a genuine low-frequency one. No digital filter can separate them.
- [3] Sampling isn't linear time-invariant in that way: order matters.
- [4] Noise and interference above $f_s/2$ will still alias into your band.
:::
:::

::: check
kind: parts
given: B = 3.4 | 15 | 20; g = 1.2 | 4

## A signal is limited to {B} kHz and must leave a guard band of {g} kHz below the first alias.

::: part
answer: 2*B + g
unit: kHz
tolerance: 0.5%

### What sampling rate does that take?

::: misses
- [2*B] That's the bare Nyquist rate, with no guard band.
- [any] The first alias of $B$ lands at $f_s - B$, which must be at least $B + g$.
:::
:::
:::

::: check
kind: derivation
vars: fs = 1..100, N = 100..10000

## A DFT of $N$ samples taken at $f_s$ (kHz).

::: step
answer: fs/N*1000

### What is the bin spacing, in Hz?
:::

::: step
answer: N/fs

### How long a record is that, in ms?
:::

::: right
Right. The bin spacing is the reciprocal of the record length.
:::
:::

::: explain
## Why does a tone above half the sample rate show up at a lower frequency in sampled data?

::: model
Samples only record the signal at the sampling instants. A sinusoid that turns more than half a cycle between samples lands at the same points it would if it had turned a little less than a full cycle the other way, which is exactly what a lower frequency does. Since the samples are identical, nothing in the data can distinguish the two, and the high tone appears as its lower alias, $|f - kf_s|$.
:::
:::

::: practice

::: check
given: fs = 10 | 20 | 50; r = 0.8 | 0.9; let f = fs*r
answer: fs - f
unit: kHz
tolerance: 0.5%

## A {f} kHz tone is sampled at {fs} kHz. What frequency does it alias to?

::: misses
- [f] It's above $f_s/2$, so it aliases.
- [any] $|f - f_s|$.
:::
:::

::: check
given: f = 200 | 400 | 1000; N = 1000 | 2000; fs = 4000 | 8000
answer: f*N/fs
tolerance: 0.5%

## A {f} Hz tone is in a DFT of {N} samples at {fs} Hz. Which bin number is it in?

::: misses
- [f*fs/N] Bin k is at $kf_s/N$, so $k = fN/f_s$.
- [any] $k = f N / f_s$.
:::
:::

::: check
given: T = 0.1 | 0.5 | 2 | 10
answer: 1/T
unit: Hz
tolerance: 0.5%

## A DFT is taken of a {T} s record. What is its frequency resolution?

::: misses
- [T] It's one over the record length.
- [any] Bin spacing is $1/T$.
:::
:::
:::
