I needed a 95% binomial confidence interval on a machine with no scientific stack: no scipy, no statsmodels, plain Python and a deadline. Clopper-Pearson is a two-sentence idea — invert the binomial test at each end — and it is also, I learned in one afternoon, a function you can get wrong in three quite different ways without a single exception being raised.
This is the version that passes, the three that did not, and the small set of hand-checkable numbers that separates them.
The version that passes
from math import comb def cdf(k, n, p): """P(X <= k) for X ~ Binomial(n, p). DECREASING in p.""" if p <= 0.0: return 1.0 if p >= 1.0: return 0.0 if k < n else 1.0 return sum(comb(n, i) * p**i * (1 - p)**(n - i) for i in range(k + 1)) def root_decreasing(f, target): """f strictly decreasing on [0,1]; return p with f(p) == target.""" lo, hi = 0.0, 1.0 for _ in range(300): mid = (lo + hi) / 2 if f(mid) > target: lo = mid else: hi = mid return (lo + hi) / 2 def cp(k, n, conf=0.95): a = 1 - conf lower = 0.0 if k == 0 else root_decreasing(lambda p: cdf(k - 1, n, p), 1 - a / 2) upper = 1.0 if k == n else root_decreasing(lambda p: cdf(k, n, p), a / 2) return 100 * lower, 100 * upper Two facts do all the work, and both are worth saying out loud because I got each of them wrong once.
The binomial CDF is decreasing in p. More success probability means less chance of landing at or below k. Every bisection below depends on that direction, and a bisection with the comparison flipped does not raise: it converges, smoothly and confidently, on the wrong end of the interval.
The two bounds are roots of the same family, shifted by one. The lower bound solves P(X ≤ k−1 | p) = 1 − α/2; the upper solves P(X ≤ k | p) = α/2. Write both with cdf(k, …) and the lower bound comes out too high — which is what my first version did, in the opposite direction from the bug before it.
The degenerate ends are returned explicitly, not solved: with k = 0 the lower bound is 0, with k = n the upper is 100. At those two points the answer is a closed form, and that is exactly why they are the best places to check the solver.
The numbers to check against
CP( 0, 10) = [ 0.00, 30.85] CP( 5, 10) = [ 18.71, 81.29] CP(10, 10) = [ 69.15, 100.00] CP( 2, 54) = [ 0.45, 12.75] CP(13, 18) = [ 46.52, 90.31] The first and third have closed forms you can compute in your head: for k = 0, the upper bound is 1 − (α/2)^(1/n) = 1 − 0.025^0.1 = 30.85%; for k = n it is (α/2)^(1/n) = 69.15%. If your routine disagrees with those two, nothing else it prints is worth reading.
For the middle one, compute the CDF directly and watch the bracket close: P(X ≤ 2 | n=54, p=0.125) = 0.028008, and at p = 0.1275 it is 0.024967. The root where that equals 0.025 sits at 12.75%. Two multiplications of this kind pin any implementation down to four decimals, which is more precision than the interval is ever quoted at.
The three ways I broke it
1. An incomplete beta called with the wrong argument. My first version used the continued fraction for the regularized incomplete beta, which has a symmetry you have to get right: in the upper branch the term is bt(1-x, b, a), and I passed bt(x, b, a). Every value it printed was plausible. Every upper bound was too low — CP(0,10) came out at 15.4% against the true 30.85%, almost exactly half, and CP(5,10) at 75.2% against 81.29%. The one case that looked right, k = n, is the case where the upper bound is pinned at 100 by the degenerate branch and never reaches the solver at all. Three of the eight endpoints I checked were wrong and the code had run to completion.
2. The monotonicity asserted backwards. I threw the incomplete beta away and rebuilt on the exact binomial CDF, which seemed like the safer choice, and then wrote the bisection as though the CDF increased in p. The result is not a wrong-looking number: it is the ends of the search interval. CP(0,10) printed [0.00, 100.00], CP(5,10) printed [0.00, 0.00]. A root-finder with the sign flipped returns the corner it was aimed at, and the corner is always a valid-looking percentage.
3. The reference value was the wrong one. With the solver fixed, four of my five checks passed and CP(2,54) came out at 12.75% against the 12.05% I had typed from memory. The routine was right; the expectation was a guess. That is the failure mode a hand-typed test set has: it checks the code against whatever you believed when you wrote the list, so it catches a real bug and blesses a typo with the same green tick. The fix is not a better memory, it is a reference value that carries its own derivation — here, the two CDF evaluations that bracket the root, printed next to it.
What a selftest for this actually needs
- One value from each degenerate end. k = 0 and k = n, where the answer is a closed form. These are the two places a solver fails loudest, because the true answer cannot be approximated into looking plausible.
- One mid-table value with its derivation printed. Not "12.75" alone, but the two CDF evaluations that bracket it. A number without its bracket is a claim; the bracket is the check.
- One value where the wrong answer is exactly half the right one. Mine was CP(0,10). Bugs in the incomplete beta tend to be symmetric errors of that size, and a case where the ratio is 0.5 is unmistakable at a glance in a way that 75.2 versus 81.3 is not.
The cost of all this is fifteen lines of test against fifteen lines of code, which is the cheapest ratio I know for a function whose output nobody re-derives.
One note on scale: evaluating the CDF term by term is fine up to n of a few hundred. Past that the comb calls dominate and you want scipy.stats.beta.ppf — not because the arithmetic changes, but because the summation does not.
If you have an interval routine you trust, what are the known values you check it against? I would like to know what the standard set is, because mine was three numbers I chose while staring at a wrong answer.