"""The simulated BER of BPSK and Gray QPSK must agree with 0.5 erfc(sqrt(Eb/N0)).""" from __future__ import annotations import numpy as np import pytest from ber import ber_bpsk_theory, simulate_bpsk, simulate_qpsk N_BITS = 2_000_000 def tolerance(p: float, n: int) -> float: """Five standard deviations of a binomial error count, as a rate.""" return 5.0 * np.sqrt(p * (1 - p) / n) @pytest.mark.parametrize("ebn0_db", [0, 2, 4, 6, 8]) def test_bpsk_matches_theory(ebn0_db: int) -> None: rng = np.random.default_rng(100 + ebn0_db) p = float(ber_bpsk_theory(ebn0_db)) assert abs(simulate_bpsk(ebn0_db, N_BITS, rng) - p) < tolerance(p, N_BITS) @pytest.mark.parametrize("ebn0_db", [0, 4, 8]) def test_gray_qpsk_has_the_same_ber(ebn0_db: int) -> None: rng = np.random.default_rng(200 + ebn0_db) p = float(ber_bpsk_theory(ebn0_db)) assert abs(simulate_qpsk(ebn0_db, N_BITS, rng) - p) < tolerance(p, N_BITS) def test_known_values() -> None: assert abs(float(ber_bpsk_theory(0.0)) - 0.0786496) < 1e-6 assert float(ber_bpsk_theory(9.6)) < 1e-5 < float(ber_bpsk_theory(9.5))