"""Confidence intervals for a success rate measured over n independent trials. Run as a script for the worked examples from the lesson: python stats.py """ from __future__ import annotations import math from scipy.stats import norm def z_value(confidence: float = 0.95) -> float: """Two-sided standard normal quantile, e.g. 1.960 for 95 %.""" if not 0.0 < confidence < 1.0: raise ValueError("confidence must be between 0 and 1") return float(norm.ppf(0.5 + confidence / 2.0)) def _check(successes: int, n: int) -> None: if n <= 0: raise ValueError("n must be positive") if not 0 <= successes <= n: raise ValueError("successes must be between 0 and n") def wilson_interval(successes: int, n: int, confidence: float = 0.95) -> tuple[float, float]: """Wilson score interval for a binomial proportion.""" _check(successes, n) z = z_value(confidence) p = successes / n denom = 1.0 + z**2 / n centre = (p + z**2 / (2 * n)) / denom half = (z / denom) * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) return max(0.0, centre - half), min(1.0, centre + half) def wald_interval(successes: int, n: int, confidence: float = 0.95) -> tuple[float, float]: """Normal-approximation (Wald) interval p +- z sqrt(p(1-p)/n). Shown for comparison only; it is too narrow for small n and collapses to a single point at 0 or n successes.""" _check(successes, n) z = z_value(confidence) p = successes / n half = z * math.sqrt(p * (1 - p) / n) return p - half, p + half def main() -> None: print(f"z for 95 %: {z_value(0.95):.4f}") print(f"{'result':<10}{'Wald 95 %':>20}{'Wilson 95 %':>20}") for k, n in [(18, 20), (20, 20), (9, 10), (45, 50), (90, 100)]: lo_w, hi_w = wald_interval(k, n) lo, hi = wilson_interval(k, n) print(f"{f'{k}/{n}':<10}{f'[{lo_w:.3f}, {hi_w:.3f}]':>20}{f'[{lo:.3f}, {hi:.3f}]':>20}") if __name__ == "__main__": main()