#467Wilson Confidence Interval (Proportion)Easy

Wilson Confidence Interval (Proportion)

Background

The Wilson score interval is the proper confidence interval for a proportion. It corrects the canonical Wald interval's pathologies at small nn and near p=0p = 0 or p=1p = 1, where Wald can give nonsensical bounds outside [0,1][0, 1].

Problem statement

Implement wilson_ci(successes, n, alpha=0.05, z=None):

p^=s/n,centre=p^+z22n1+z2n,half-width=z1+z2/np^(1p^)n+z24n2\hat{p} = s/n,\qquad \text{centre} = \frac{\hat{p} + \frac{z^2}{2n}}{1 + \frac{z^2}{n}},\qquad \text{half-width} = \frac{z}{1 + z^2/n}\sqrt{\frac{\hat{p}(1-\hat{p})}{n} + \frac{z^2}{4n^2}}

Return (lo, hi) clipped to [0,1][0, 1].

Input

  • successes - int >= 0.
  • n - int >= 1, total trials, nn \ge successes.
  • alpha - significance (default 0.050.05 → 95% CI).
  • z - optional override of the z-score (default: 1.96 for alpha=0.05).

Output

  • (lo, hi) - tuple of plain Python floats.

Examples

Input: successes=8, n=10, alpha=0.05
Output: roughly (0.49, 0.94)

Constraints

  • ValueError on bad inputs (n < 1, successes < 0, successes > n).
  • Output bounded in [0,1][0, 1].

Notes

  • vs Wald. Wald = p^±zp^(1p^)/n\hat p \pm z\sqrt{\hat p(1-\hat p)/n}. At s=0,n=10s = 0, n = 10 Wald gives [0,0][0, 0]; Wilson gives a non-degenerate upper bound.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • example: successes=8, n=10, 95% CI
  • reference: symmetric interval for s=50, n=100
  • sample: zero successes gives non-degenerate upper bound