A supplier promises that only 10% of its circuit boards are faulty. An inspector tests n boards and finds k faulty ones. Under the null hypothesis "the fault rate is p0", the number of faulty boards X follows the binomial distribution P(X = j) = C(n, j) p0^j (1 - p0)^(n - j).
Write binomial_p_values(k, n, p0) that returns a tuple of three exact p-values:
upper:P(X >= k), the evidence that the rate is higher than claimed,lower:P(X <= k), the evidence that it is lower,two_sided: the total probability of all outcomesjthat are at most as likely as the observed one,P(X = j) <= P(X = k). To be safe from rounding, countjwhenP(X = j) <= P(X = k) · (1 + 1e-7).
Cap each value at 1.0 (rounding can push a sum of probabilities slightly above 1).
Examples
Input: k = 60, n = 100, p0 = 0.5
Output: (0.028443966820489622, 0.9823998998911305, 0.056887933640979264)
Explanation: for a fair coin the two tails are mirror images, so the two-sided value
is twice the upper tail: 60 or more heads, or 40 or fewer.
Input: k = 9, n = 40, p0 = 0.1
Output: (0.015495305414444488, 0.9949369463421593, 0.015495305414444488)
Explanation: 4 faulty boards are expected. Even 0 faulty (probability 0.0148) is more
likely than 9 (0.0100), so no outcome in the lower tail is as surprising as the observed
one, and the two-sided p-value equals the upper tail.
Constraints
1 <= n <= 10**4,0 <= k <= n,0 < p0 < 1- floats are compared with a tolerance of
1e-6
Goals
- Compute exact binomial probabilities under a null hypothesis
- Turn an observed count into one-sided p-values in each direction
- Compute a two-sided p-value that works for lopsided null distributions