---
title: "Detection lab: error rates by simulation"
heading: Monte Carlo bit and symbol error rates for BPSK, 16-QAM and 8-PSK against their formulas, the MAP threshold for unequal priors, and how many bits a measurement needs
eyebrow: S8 · Lesson 24 · Detection lab
xp: 60
---

::: hook
Every error-rate formula in lessons 12 to 20 rests on assumptions: Gaussian noise, perfect timing, a known channel, the right threshold. A simulation checks them all at once. You generate random symbols, add noise of exactly the right variance, decide, and count mistakes; if the count lands on the formula, the formula and the simulation agree about every scale factor. In this lab you'll build the simulations engineers use to check receivers, and learn how many bits it takes before a simulated error rate means anything.
:::

::: play
- The curves are BPSK's bit error probability on an AWGN channel, $Q(\sqrt{2E_b/N_0})$, and on a Rayleigh-fading channel, $\frac12\left(1 - \sqrt{\bar\gamma/(1 + \bar\gamma)}\right)$.
- Measuring a rate of p to ±10% takes about 100 errors, so about 100/p bits: a million for 10⁻⁴, a hundred million for 10⁻⁶.
- That cost is why simulations stop around 10⁻⁶ and why low error rates are extrapolated from formulas or measured with special techniques.
:::

```sim plot
view: graph
x: E = 0..30 dB
y: P = 1e-7..0.5 log
plot: Q(sqrt(2*10^(E/10))) | label: BPSK, AWGN
plot: 0.5*(1 - sqrt(10^(E/10)/(1 + 10^(E/10)))) | label: BPSK, Rayleigh
```

::: predict
## A simulation of a link whose true bit error rate is 10⁻⁵ should report that rate within about ±10%. How many bits must it send?

- [ ] About 10 000
- [ ] About 10⁵
- [x] About 10⁷
- [ ] About 10⁹

::: reveal
Errors arrive almost as a Poisson process, so k counted errors have a standard deviation of about $\sqrt k$: a relative error of $1/\sqrt k$. ±10% needs about 100 errors, and at 10⁻⁵ that takes 10⁷ bits. Halving the uncertainty takes four times as many.
:::
:::

::: nameit
## What the lab computes

- **Noise scaling.** For symbols of average energy $E_s$ carrying $\log_2M$ bits, $E_b = E_s/\log_2M$, and each real noise dimension has variance $N_0/2$. With unit-energy BPSK, $\sigma = \sqrt{1/(2E_b/N_0)}$.
- **Square QAM.** With levels ±1 and ±3 per axis (average $E_s$ = 10), each axis errs with $P_\sqrt{M} = 2(1 - 1/\sqrt M)Q\left(\sqrt{3E_s/((M - 1)N_0)}\right)$, and the symbol error rate is $1 - (1 - P_\sqrt{M})^2$.
- **M-PSK.** At high SNR, $P_s \approx 2Q\left(\sqrt{2E_s/N_0}\sin(\pi/M)\right)$.
- **MAP threshold.** For ±A with prior $p_1$ on +A and noise σ, the threshold that minimizes errors is $t = \frac{\sigma^2}{2A}\ln\frac{1 - p_1}{p_1}$, with error probability $p_1Q\left(\frac{A - t}{\sigma}\right) + (1 - p_1)Q\left(\frac{A + t}{\sigma}\right)$.
- **Confidence.** n trials with true rate p give an estimate with standard deviation $\sqrt{p(1 - p)/n}$; a relative uncertainty r needs $n = (1 - p)/(pr^2)$.
:::

::: check
kind: python

## Write `ber_bpsk(EbN0_db, n, seed)`: send n random bits as ±1 through AWGN at the given Eb/N0, decide by sign, and return the fraction of errors. Use `random.Random(seed)`.

```python starter
def ber_bpsk(EbN0_db, n, seed):
    return 0.0
```

```python solution
import math, random

def ber_bpsk(EbN0_db, n, seed):
    r = random.Random(seed)
    s = math.sqrt(1 / (2 * 10 ** (EbN0_db / 10)))
    e = 0
    for _ in range(n):
        b = r.random() < 0.5
        y = (1 if b else -1) + r.gauss(0, s)
        e += (y > 0) != b
    return e / n
```

```python tests
import math
Q = lambda x: 0.5 * math.erfc(x / math.sqrt(2))
for E, n in ((4, 100000), (7, 200000)):
    p = Q(math.sqrt(2 * 10 ** (E / 10)))
    assert abs(ber_bpsk(E, n, 11) - p) < 4 * math.sqrt(p / n), f"At {E} dB the rate should be near {p:.2e}."
```

::: right
Right. If σ were off by √2 (a common slip, forgetting that $N_0/2$ is the variance per dimension), the measured curve would shift by 3 dB and miss by a factor of many.
:::
:::

::: check
kind: python

## Write `ser_qam16(EbN0_db, n, seed)`: send n random 16-QAM symbols with levels ±1, ±3 per axis (Es = 10), add complex AWGN at the given Eb/N0, decide each axis by the nearest level, and return the symbol error rate.

```python starter
def ser_qam16(EbN0_db, n, seed):
    return 0.0
```

```python solution
import math, random

def ser_qam16(EbN0_db, n, seed):
    r = random.Random(seed)
    N0 = (10 / 4) / 10 ** (EbN0_db / 10)
    s = math.sqrt(N0 / 2)
    lv = (-3, -1, 1, 3)
    near = lambda v: min(lv, key=lambda l: abs(v - l))
    e = 0
    for _ in range(n):
        a, b = r.choice(lv), r.choice(lv)
        e += near(a + r.gauss(0, s)) != a or near(b + r.gauss(0, s)) != b
    return e / n
```

```python tests
import math
Q = lambda x: 0.5 * math.erfc(x / math.sqrt(2))
for E in (8, 10):
    g = 10 ** (E / 10)
    pa = 2 * (1 - 1 / 4) * Q(math.sqrt(3 * 4 * g / 15))
    p = 1 - (1 - pa) ** 2
    assert abs(ser_qam16(E, 60000, 3) - p) < 4 * math.sqrt(p / 60000), f"At {E} dB the symbol error rate should be near {p:.2e}."
```

::: right
Right. The exact square-QAM formula holds because the two axes' decisions are independent; only the corner and edge points' fewer neighbors make it differ from four times a single Q.
:::
:::

::: check
kind: python

## Write `map_threshold(A, sigma, p1)` and `error_prob(A, sigma, p1, t)` for antipodal ±A with prior p1 on +A, noise σ and threshold t.

```python starter
def map_threshold(A, sigma, p1):
    return 0.0

def error_prob(A, sigma, p1, t):
    return 0.5
```

```python solution
import math

def map_threshold(A, sigma, p1):
    return sigma ** 2 / (2 * A) * math.log((1 - p1) / p1)

def error_prob(A, sigma, p1, t):
    Q = lambda x: 0.5 * math.erfc(x / math.sqrt(2))
    return p1 * Q((A - t) / sigma) + (1 - p1) * Q((A + t) / sigma)
```

```python tests
import math
Q = lambda x: 0.5 * math.erfc(x / math.sqrt(2))
assert abs(error_prob(1, 0.5, 0.5, 0) - Q(2)) < 1e-15, "Equal priors, threshold 0: Q(A/σ)."
for A, s, p1 in ((1, 0.5, 0.8), (1, 0.7, 0.1), (2, 1.5, 0.95)):
    t = map_threshold(A, s, p1)
    assert abs(t - s * s / (2 * A) * math.log((1 - p1) / p1)) < 1e-12, "The MAP threshold."
    assert error_prob(A, s, p1, t) <= min(error_prob(A, s, p1, t + d) for d in (-0.01, 0.01, -0.1, 0.1)), "It minimizes the error probability."
    assert error_prob(A, s, p1, t) < error_prob(A, s, p1, 0), "Moving the threshold beats ignoring the priors."
```

::: right
Right. The threshold moves toward the less likely symbol, so the likely one is decided correctly more often; at high SNR the shift shrinks as σ².
:::
:::

::: check
kind: python

## Write `ser_mpsk(M, EsN0_db, n, seed)`: simulate n M-PSK symbols on the unit circle in complex AWGN at the given Es/N0, decide by the nearest phase, and return the symbol error rate; and `bits_needed(p, rel)`: how many trials measure a rate p with relative standard deviation rel.

```python starter
def ser_mpsk(M, EsN0_db, n, seed):
    return 0.0

def bits_needed(p, rel):
    return 0
```

```python solution
import cmath, math, random

def ser_mpsk(M, EsN0_db, n, seed):
    r = random.Random(seed)
    s = math.sqrt(1 / (2 * 10 ** (EsN0_db / 10)))
    e = 0
    for _ in range(n):
        k = r.randrange(M)
        y = cmath.exp(2j * math.pi * k / M) + complex(r.gauss(0, s), r.gauss(0, s))
        e += round(cmath.phase(y) * M / (2 * math.pi)) % M != k
    return e / n

def bits_needed(p, rel):
    return (1 - p) / (p * rel ** 2)
```

```python tests
import math
Q = lambda x: 0.5 * math.erfc(x / math.sqrt(2))
for M, E in ((8, 14), (4, 10)):
    p = 2 * Q(math.sqrt(2 * 10 ** (E / 10)) * math.sin(math.pi / M))
    assert abs(ser_mpsk(M, E, 100000, 8) - p) < 4 * math.sqrt(p / 100000) + 0.02 * p, f"{M}-PSK at {E} dB: about {p:.2e}."
assert abs(bits_needed(1e-5, 0.1) - 9.9999e6) < 1, "10⁻⁵ to ±10%: about 10⁷ trials."
```

::: right
Right. For QPSK the high-SNR formula double-counts the rare symbols that err both ways, which is why it's an approximation; at 10 dB the difference is far below the simulation's noise.
:::
:::

::: explain
## Why is a simulated error rate that matches its formula good evidence that a receiver model is right, and what can such a match fail to reveal?

::: model
An error rate depends steeply on the signal-to-noise ratio, so a mistake in any scale factor, the symbol energy, the noise variance per dimension, the bits per symbol or a filter's gain, shifts the simulated curve by decibels and makes it miss the formula by a large factor. Matching across several SNRs therefore confirms that all those factors are consistent. What it can't reveal is anything the formula and the simulation share: if both assume perfect timing, a known channel or Gaussian noise, the agreement says nothing about how the real receiver behaves when those assumptions fail, so impairments have to be added to the simulation deliberately.
:::
:::
