"""Bit error rate of BPSK and Gray-coded QPSK in additive white Gaussian noise. Theory: with antipodal symbols +-sqrt(Eb) and noise of variance N0/2 per dimension, a bit is wrong when the noise exceeds sqrt(Eb), so Pb = Q(sqrt(2 Eb/N0)) = 0.5 * erfc(sqrt(Eb/N0)). Gray-coded QPSK is two BPSK signals on I and Q, so its bit error rate is the same. """ from __future__ import annotations import numpy as np from scipy.special import erfc def ber_bpsk_theory(ebn0_db: float | np.ndarray) -> float | np.ndarray: ebn0 = 10.0 ** (np.asarray(ebn0_db) / 10.0) return 0.5 * erfc(np.sqrt(ebn0)) def simulate_bpsk(ebn0_db: float, n_bits: int, rng: np.random.Generator) -> float: """Return the measured bit error rate. Eb = 1, so N0 = 1 / (Eb/N0).""" bits = rng.integers(0, 2, n_bits) symbols = 1.0 - 2.0 * bits # 0 -> +1, 1 -> -1 n0 = 1.0 / 10.0 ** (ebn0_db / 10.0) received = symbols + rng.normal(0.0, np.sqrt(n0 / 2), n_bits) decided = (received < 0).astype(int) return float(np.mean(decided != bits)) def simulate_qpsk(ebn0_db: float, n_bits: int, rng: np.random.Generator) -> float: """Gray QPSK: bit pairs (b1, b0) -> I = +-1, Q = +-1, so Es = 2 and Eb = 1.""" n_sym = n_bits // 2 bits = rng.integers(0, 2, (n_sym, 2)) i = 1.0 - 2.0 * bits[:, 0] q = 1.0 - 2.0 * bits[:, 1] n0 = 1.0 / 10.0 ** (ebn0_db / 10.0) sigma = np.sqrt(n0 / 2) ri = i + rng.normal(0.0, sigma, n_sym) rq = q + rng.normal(0.0, sigma, n_sym) decided = np.stack(((ri < 0).astype(int), (rq < 0).astype(int)), axis=1) return float(np.mean(decided != bits)) if __name__ == "__main__": rng = np.random.default_rng(2026) for snr in range(0, 9): sim = simulate_bpsk(snr, 2_000_000, rng) print(f"Eb/N0 = {snr} dB theory {ber_bpsk_theory(snr):.3e} simulated {sim:.3e}")