Exact Binomial Tail Test Across Unequal Sample Sizes
Medium · Statistics & Math · Data Scientist · Technical Screen
Problem Statement
A participant claims they can sense the suit of a face-down playing card drawn uniformly and independently with replacement from the 4 standard suits. If the participant has no genuine ability and is purely guessing, each trial succeeds with baseline probability p0 = 1/4 = 0.25.
Two separate trial sets are recorded:
- Trial Set 1:
n = 4draws,k = 3correct (75.0%apparent accuracy). - Trial Set 2:
n = 48draws,k = 24correct (50.0%apparent accuracy).
To evaluate directional claims of this form programmatically across arbitrary sample sizes, implement exact_binomial_upper_tail:
def exact_binomial_upper_tail(n: int, k: int, p: float) -> float:
Given n independent Bernoulli trials with per-trial success probability p, return the exact one-sided upper-tail probability P(X >= k) for X ~ Binomial(n, p):
- Hypothesis & Modeling Context: Under
H0: p = p0against the directional alternativeH1: p > p0,P(X >= k | n, p0)is the exact one-sided p-value — allowing direct comparison of small-sample high-percentage outcomes against larger-sample moderate-percentage outcomes at significance levelalpha = 0.05(as well as comparison against a continuity-corrected normal approximation whenn * pandn * (1 - p)are large). - Boundary & Validation Rules:
- Raise
ValueErrorifn < 0or ifpis outside[0.0, 1.0](includingNaN). - Return
1.0wheneverk <= 0, and return0.0wheneverk > n(including whenn == 0). - Handle degenerate probabilities
p == 0.0andp == 1.0cleanly without domain errors. - Maintain numerical accuracy for large
n(whereC(n, j)overflows 64-bit floats), tinyp, and extreme upper tails (where1.0 - P(X < k)loses precision to catastrophic cancellation).
- Raise
Examples
Example 1
Input: n = 4, k = 3, p = 0.25
Output: 0.05078125
In Trial Set 1, achieving at least 3 hits out of 4 at p = 0.25 adds two binomial terms: C(4, 3) * 0.25^3 * 0.75^1 = 12 / 256 = 0.046875 and C(4, 4) * 0.25^4 * 0.75^0 = 1 / 256 = 0.00390625, totaling 13 / 256 = 0.05078125. Despite the 75.0% hit rate, 0.05078125 > 0.05, so H0 is not rejected at alpha = 0.05.
Example 2
Input: n = 48, k = 24, p = 0.25
Output: 0.0001664837504420403
In Trial Set 2, expected hits under H0 are 48 * 0.25 = 12 with standard deviation sqrt(48 * 0.25 * 0.75) = 3. Summing P(X = j) over j = 24..48 gives ~1.665e-4, which is far below alpha = 0.05 — even though 50.0% is lower than Trial Set 1's 75.0% hit rate, the 48-trial sample provides decisive statistical evidence against pure chance.
Constraints
n >= 0(typically up to10^4; negativenmust raiseValueError).kcan be any integer, includingk <= 0andk > n.0.0 <= p <= 1.0(values outside[0.0, 1.0]orNaNmust raiseValueError).- Returned probabilities must lie in
[0.0, 1.0]and preserve relative precision even when the exact tail is far below10^-16.
Step-by-step walkthrough
Restate the problem and what the code computes
A participant tries to name the suit of a face-down playing card drawn uniformly with replacement from the 4 suits. Under pure chance, each guess succeeds with probability
p0 = 1/4 = 0.25. We want to evaluate two trial sets—Trial Set 1 (k = 3hits inn = 4attempts) and Trial Set 2 (k = 24hits inn = 48attempts)—and implementexact_binomial_upper_tail(n, k, p)to compute the exact one-sided upper-tail probability:P(X >= k) for X ~ Binomial(n, p) = P(X = k) + P(X = k + 1) + ... + P(X = n)Visually, out of all
n + 1possible hit counts0, 1, ..., n, the one-sided p-value adds up the shaded upper tail fromkthroughn:Trial Set 1 (n = 4, k = 3, p = 0.25): j = 0 j = 1 j = 2 [ j = 3 j = 4 ] <-- sum j = 3..4 0.3164 0.4219 0.2109 [ 0.046875 + 0.00390625 ] = 0.05078125 Trial Set 2 (n = 48, k = 24, p = 0.25): j = 0 ... j = 12 (mean) ... j = 23 [ j = 24 j = 25 ... j = 48 ] [ <---- sum j = 24..48 ---> ] ≈ 1.665e-4Once
exact_binomial_upper_tailis built, Trial Set 1 isexact_binomial_upper_tail(4, 3, 0.25)and Trial Set 2 isexact_binomial_upper_tail(48, 24, 0.25). Let us walk through the statistical framing first, then build a numerically safe log-space implementation.Formulate the hypothesis test and binomial assumptions
Let
pbe the participant's true single-trial probability of naming the concealed suit. A null hypothesis (H0) is the baseline "pure chance" claim we test against, and the alternative hypothesis (H1) is the directional effect we look for evidence to support:- Null hypothesis (
H0):p = 0.25(accuracy is no better than random guessing across 4 equally likely suits; equivalentlyp <= 0.25). - Alternative hypothesis (
H1):p > 0.25(the participant identifies suits above chance). We run a one-sided test because only an unusually high hit count supports above-chance perception; scoring below 25% provides zero evidence for the claim.
Under
H0, the total hit count followsBinomial(n, 0.25)when five assumptions hold:- Pre-specified trial count (
n):n = 4andn = 48are fixed before observing outcomes rather than halting as soon as a streak looks impressive (optional stopping inflates Type I error). - Binary outcomes: Every draw produces either a hit (
1) or a miss (0). - Mutual independence: Past outcomes provide zero information about upcoming draws; sampling with replacement ensures the 4 suits stay uniformly distributed even if previous cards were revealed.
- Identical success probability (
p = 0.25): Because all 4 suits have probability1/4on every draw, any guessing strategy without genuine signal succeeds with probability1/4each time. - Sensory blinding: Physical cues (bent corners, card markings, dealer reactions) cannot leak the suit.
- Null hypothesis (
Compute Trial Set 1 by hand
The binomial probability mass function (PMF) gives the exact probability of observing
jhits inntrials:P(X = j) = C(n, j) * p^j * (1 - p)^(n - j), whereC(n, j) = n! / (j! * (n - j)!)counts how many subsets ofjtrials can be the hits,p^jis the probability of thosejhits, and(1 - p)^(n - j)is the probability of then - jmisses.For Trial Set 1 (
n = 4,k = 3,p = 0.25), "at least 3 hits" meansX = 3orX = 4:P(X = 3) = C(4, 3) * (0.25)^3 * (0.75)^1 = 4 * (1/64) * (3/4) = 12 / 256 = 0.046875 P(X = 4) = C(4, 4) * (0.25)^4 * (0.75)^0 = 1 * (1/256) * 1 = 1 / 256 = 0.00390625 -------------------------------------------------------------------------------------- P(X >= 3) = 0.046875 + 0.00390625 = 13 / 256 = 0.05078125At significance threshold
alpha = 0.05,0.05078125 > 0.05, so we fail to rejectH0. Pure luck alone scores 3 or 4 out of 4 roughly once every 20 sessions (5.08%). Withn = 4, only a perfect4 / 4(p = 1 / 256 ≈ 0.0039) crossesalpha = 0.05.Approximate and verify Trial Set 2
For Trial Set 2 (
n = 48,k = 24,p = 0.25), underH0the expected hit count ismean = n * p = 12and the standard deviation issd = sqrt(n * p * (1 - p)) = sqrt(48 * 0.25 * 0.75) = sqrt(9) = 3. Because bothn * p = 12 >= 10andn * (1 - p) = 36 >= 10, a normal curveNormal(mean = 12, sd = 3)approximates the center well.When approximating discrete integer counts with a continuous density, integer
mspans[m - 0.5, m + 0.5). A continuity correction shifts the cutoff from24down to23.5so the continuous integral captures the full probability bar centered at24:Discrete bars: ... | Y = 23 | Y = 24 | Y = 25 | ... Real number line: ... 22.5 23.5 24.5 25.5 ... ^---- Y >= 24 starts at 23.5 Without continuity correction: z = (24.0 - 12) / 3 = 4.000 -> P(Z >= 4.000) ≈ 3.17e-5 With continuity correction: z = (23.5 - 12) / 3 = 3.833 -> P(Z >= 3.833) ≈ 6.32e-5 Exact binomial sum (j=24..48): P(Y >= 24) ≈ 1.66e-4All three figures lie far below
alpha = 0.05, so we strongly rejectH0. Notice that even after continuity correction, the symmetric normal tail still underestimates the exact binomial tail by about2.6xbecausep = 0.25 < 0.50skewsBinomial(48, 0.25)positively to the right.Compare the two trial sets: effect size vs. sample size
Placing both trial sets side by side explains why a bigger raw percentage does not guarantee stronger statistical evidence:
Metric Trial Set 1 Trial Set 2 ----------------------------------- ------------------ ------------------ Sample size (n) and hits (k) 3 / 4 24 / 48 Observed accuracy (k / n) 75.0% 50.0% Apparent lift over 25% baseline +50.0 pct points +25.0 pct points Standard error under H0: sqrt(pq/n) 0.2165 (21.7%) 0.0625 (6.25%) Exact one-sided p-value 0.0508 1.66e-4 Decision at alpha = 0.05 Do NOT reject H0 Reject H0Trial Set 1 exhibits double the effect size (
+50.0vs.+25.0percentage points above chance), yet misses significance because the standard error (sqrt(p * (1 - p) / n)) shrinks at rate1 / sqrt(n). Atn = 4, sampling noise easily swings accuracy by +/-21.7 percentage points; atn = 48, noise shrinks to +/-6.25 percentage points, placing a +25-point lift 4 standard errors above baseline.In practice, tiny samples have low statistical power (missing substantial real effects), while huge samples can make tiny, practically trivial lifts look "statistically significant." Always report confidence intervals alongside p-values.
Compute exact binomial tails safely in log space
Evaluating
math.comb(n, j) * (p ** j) * ((1 - p) ** (n - j))directly breaks down in three common numerical regimes:- Integer-to-float overflow: At
n = 2000, j = 1000,C(2000, 1000)is roughly10^601, exceeding the 64-bit float ceiling (~1.8e308) and raisingOverflowError. - Power underflow: At
n = 5000, j = 1250, p = 0.25,0.25 ** 1250underflows straight to0.0even thoughP(X = 1250)is around0.013. - Catastrophic cancellation from
1 - lower_tail: Forn = 100, k = 90, p = 0.2, the true upper tail is~2.37e-51, whereas1.0 - P(X <= 89)subtracts a value indistinguishable from1.0in 53-bit float precision (ulp~1.1e-16), wiping out every significant digit.
Summing the upper tail
j = k..ndirectly in natural-log space avoids all three pitfalls:ln P(X = j) = ln(n!) - ln(j!) - ln((n - j)!) + j * ln(p) + (n - j) * ln(1 - p)math.lgamma(m + 1)computesln(m!)inO(1)time without constructing huge integers,math.log1p(-p)preserves accuracy whenpis near0, andmath.fsumsums the exponentiated probabilities without rounding drift. Before taking logarithms, we validate inputs (n >= 0,0 <= p <= 1), handle count boundaries (k <= 0 -> 1.0,k > n -> 0.0), and short-circuitp == 0.0orp == 1.0.def binomial_log_pmf(n: int, j: int, p: float) -> float: """Return ln P(X = j) for X ~ Binomial(n, p), assuming 0 < p < 1 and 0 <= j <= n.""" # Since m! = Gamma(m + 1), lgamma(m + 1) gives ln(m!) without computing huge integers. log_combinations = ( math.lgamma(n + 1) - math.lgamma(j + 1) - math.lgamma(n - j + 1) ) # Compute ln(p^j) and ln((1 - p)^(n - j)) as products instead of exponentiating first. # math.log1p(-p) evaluates ln(1 - p) accurately even when p is very close to 0. log_successes = j * math.log(p) log_failures = (n - j) * math.log1p(-p) return log_combinations + log_successes + log_failures- Integer-to-float overflow: At
Complete solution
Putting parameter validation, boundary checks, and log-space upper-tail summation together gives the complete implementation:
from typing import Any, Dict, List, Optional, Set, Tuple import math def binomial_log_pmf(n: int, j: int, p: float) -> float: """Return ln P(X = j) for X ~ Binomial(n, p), assuming 0 < p < 1 and 0 <= j <= n.""" # Since m! = Gamma(m + 1), lgamma(m + 1) gives ln(m!) without computing huge integers. log_combinations = ( math.lgamma(n + 1) - math.lgamma(j + 1) - math.lgamma(n - j + 1) ) # Compute ln(p^j) and ln((1 - p)^(n - j)) as products instead of exponentiating first. # math.log1p(-p) evaluates ln(1 - p) accurately even when p is very close to 0. log_successes = j * math.log(p) log_failures = (n - j) * math.log1p(-p) return log_combinations + log_successes + log_failures def exact_binomial_upper_tail(n: int, k: int, p: float) -> float: """Return P(X >= k) for X ~ Binomial(n, p), the exact one-sided upper-tail p-value.""" # Phase 1: Validate distribution parameters (also rejects NaN because comparisons fail). if n < 0 or not (0.0 <= p <= 1.0): raise ValueError("need n >= 0 and 0 <= p <= 1") # Phase 2: Handle count boundaries before touching logarithms. # X is always in [0, n], so X >= k is guaranteed when k <= 0 and impossible when k > n. if k <= 0: return 1.0 if k > n: return 0.0 # Phase 3: Handle degenerate probabilities p == 0 and p == 1 to avoid log(0). # At this point 1 <= k <= n: if p == 0 then X is always 0 (< k); if p == 1 then X is always n (>= k). if p == 0.0: return 0.0 if p == 1.0: return 1.0 # Phase 4: Sum the upper tail directly in log space. # Avoid 1.0 - P(X < k), because subtracting a value near 1.0 erases tiny p-values (< 1e-16). # tail_probabilities: list of float terms [P(X = k), P(X = k + 1), ..., P(X = n)]. tail_probabilities: List[float] = [] for j in range(k, n + 1): log_prob = binomial_log_pmf(n, j, p) tail_probabilities.append(math.exp(log_prob)) # math.fsum adds floating-point terms without cumulative rounding drift, and min(..., 1.0) # prevents the last bit of rounding from pushing a total probability slightly above 1.0. total_probability = math.fsum(tail_probabilities) return min(total_probability, 1.0)✅ Submit now — all tests should pass.
Intuition & how it works
Think of testing a claimed card-suit psychic like judging a free-throw shooter: sinking 3 out of 4 practice tosses looks dramatic (75.0%), whereas hitting 24 out of 48 when blindfolded luck lands 25% (50.0%) is vastly stronger proof of real skill. A p-value—the probability of observing an outcome at least as extreme as the data if the person were purely guessing—captures that trade-off by combining how far the hit rate sits above baseline with how many trials support it. To compute that exact upper-tail probability in Python for any n without overflowing on giant factorials or underflowing on tiny powers, we compute the natural logarithm of each binomial term first—turning giant products into ordinary sums—and then exponentiate and sum j = k..n directly.
Judging by raw hit percentage alone fails statistically because tiny samples bounce wildly by luck, while computing math.comb(n, j) * (p ** j) * ((1 - p) ** (n - j)) directly fails numerically once n reaches the thousands. Specifically, C(2000, 1000) exceeds 10^600 and triggers OverflowError, 0.25 ** 1250 underflows to 0.0, and subtracting 1 - P(X < k) erases tiny p-values below 10^-16 because floats near 1.0 hold only ~16 decimal digits of precision.
Let us trace Example 1 (n = 4, k = 3, p = 0.25) through our log-space summation:
- Boundaries pass (n = 4 >= 0, 1 <= k <= 4, 0 < p < 1), so j loops over [3, 4].
- At j = 3: ln C(4, 3) = lgamma(5) - lgamma(4) - lgamma(2) = ln(24) - ln(6) - 0 = ln(4). Adding 3 * ln(0.25) + 1 * ln(0.75) gives ln(12 / 256), and exp(...) recovers 0.046875.
- At j = 4: ln C(4, 4) = 0. Adding 4 * ln(0.25) + 0 * ln(0.75) gives ln(1 / 256), and exp(...) recovers 0.00390625.
- math.fsum([0.046875, 0.00390625]) returns 0.05078125 (> 0.05, not significant), while the same loop on Example 2 (n = 48, k = 24, p = 0.25) sums j = 24..48 to 1.665e-4 (<< 0.05, strongly significant).
Complexity
- Time: O(n - k + 1) (at most
O(n)). AfterO(1)validation and boundary checks, the loop visits each integer hit countjfromktononce, callingO(1)math functions (lgamma,log,log1p,exp) per step, followed by one linearmath.fsumpass over then - k + 1terms. - Space: O(n - k + 1) for the
tail_probabilitieslist passed intomath.fsum(reducible toO(1)with a running float sum if memory is constrained, at a minor cost in rounding accuracy).
Edge cases
k <= 0: Since a binomial countXis always non-negative,X >= kholds with probability1.0—includingn = 0, k = 0.k > n: Scoring more hits than attempts is impossible (0.0), includingn = 0, k = 1.p = 0.0orp = 1.0: Returning beforebinomial_log_pmfavoidsmath.log(0)(ValueError) and handles deterministic outcomes cleanly (X = 0whenp = 0,X = nwhenp = 1).- Extreme upper tails (
kclose ton): Direct summation overj = k..nretains full relative precision even around10^-51, where1 - P(X < k)rounds to0.0. - Large
n(n = 2000+):math.lgammaavoids converting600+-digit integers to 64-bit floats. - Invalid inputs (
n < 0,p < 0,p > 1, orp = NaN): Rejected immediately withValueError.
Common mistakes
- Computing
P(X > k)instead ofP(X >= k). By definition, a one-sided p-value includes the observed countk("at least as extreme as observed"), so Example 1 addsj = 3andj = 4, notj = 4alone. - Using a two-sided p-value for a one-directional claim. Because only above-chance accuracy (
p > 0.25) supports suit perception, probability mass in the lower tail (X < np) is not evidence for the claim. - Shifting the continuity correction the wrong way. Integer
24covers[23.5, 24.5)on the continuous line, soY >= 24starts at23.5(z = (23.5 - 12) / 3 = 3.833), whereas24.5approximatesY >= 25. - Applying a normal approximation to tiny
nor trusting it deep in a skewed tail. Atn = 4, p = 0.25,np = 1.0violatesnp >= 10; even atn = 48, right-skewness makes the exact tail ~2.6 times larger than the continuity-corrected normal tail atz ≈ 3.83. - Confusing the p-value with
P(H0 is true)or raw effect size. A p-value isP(X >= k | H0), not the probability that the participant is guessing; conversely,75.0%onn = 4provides weaker evidence than50.0%onn = 48.
Alternative approaches
- Multiplicative term recurrence: Using
P(X = j + 1) = P(X = j) * ((n - j) / (j + 1)) * (p / (1 - p))avoids callinglgammaandexpon every iteration after computing the initial log-PMF atk(or at the modefloor((n + 1) * p)whenP(X = k)itself would underflow). - Regularized incomplete beta function: Using the identity
P(X >= k) = I_p(k, n - k + 1), where the regularized incomplete beta function integrates theBeta(k, n - k + 1)density up top, scientific libraries (scipy.stats.binom.sf(k - 1, n, p)) evaluate the tail via continued fractions in nearlyO(1)time even for hugen.
Follow-up questions
- What changes if trials draw without replacement from a finite deck of 16 cards (4 per suit) rather than sampling with replacement? Suppose the 16-card deck starts with 4 cards of each suit (reshuffled every 16 draws for Trial Set 2). If the participant receives zero feedback after each guess, marginal symmetry keeps every individual draw at
1/4success probability, and repeating one fixed suit in Trial Set 1 follows a hypergeometric distribution (the exact count distribution for sampling without replacement), givingP(X >= 3) = (C(4, 3) * C(12, 1) + C(4, 4)) / C(16, 4) = 49 / 1820 ≈ 0.0269because misses remove non-matching cards and tighten variance. However, if each drawn card is revealed before the next guess, a card-counting participant who always names whichever suit has the most cards remaining averages6.73hits per 16-card deck (20.20across48draws), lifting Trial Set 2's p-value toP(Y >= 24) ≈ 0.0968 > 0.05and wiping out statistical significance! Withholding trial-by-trial feedback or sampling with replacement closes that leak. - Under a Bayesian model with a conjugate Beta prior on p, how do the resulting posterior distributions compare between the small and large trial sets? A Beta distribution
Beta(a, b)on[0, 1]is a conjugate prior for binomial counts, updatingkhits andn - kmisses directly toBeta(a + k, b + n - k)(aandbact like prior pseudo-hits and pseudo-misses). Starting from a flatBeta(1, 1)uniform prior, Trial Set 1 (3 / 4) yieldsBeta(4, 2)(mean0.667, wide 95% credible interval[0.28, 0.95], heavily shaped by the prior's 75% mass above0.25), whereas Trial Set 2 (24 / 48) yieldsBeta(25, 25)(mean0.500, tight 95% credible interval[0.36, 0.64],P(p <= 0.25 | data) ≈ 8.03e-5, dominated by the 48 observations). ComparingH1: p ~ Beta(1, 1)against the sharp nullH0: p = 0.25via a Bayes factor—the ratio of marginal data likelihood underH1versusH0—gives only~4.27for Trial Set 1 versus~177.5for Trial Set 2. - If the participant maintains the exact 75% hit rate from Trial Set 1, what minimum trial count n is required to reject H0 at alpha = 0.05? For
k / nto equal3/4(75.0%) strictly with integer counts,nmust be a multiple of4. Atn = 4(k = 3),P(X >= 3 | n = 4, p = 0.25) = 13 / 256 ≈ 0.05078 > 0.05just misses the cutoff; at the next multiple of4,n = 8(k = 6),P(X >= 6 | n = 8, p = 0.25) = (28 * 9 + 8 * 3 + 1) / 4^8 = 277 / 65536 ≈ 0.00423 <= 0.05, so 8 trials (6 / 8correct) are required. Notice that a naive normal approximation(0.75 - 0.25) / sqrt(0.1875 / n) >= 1.645yieldsn >= 2.03 -> 3, which fails at smallnboth because3cannot produce75%and becausen = 4still exceeds0.05.
Follow-up questions
- What changes if trials draw without replacement from a finite deck of 16 cards (4 per suit) rather than sampling with replacement?
- Under a Bayesian model with a conjugate Beta prior on p, how do the resulting posterior distributions compare between the small and large trial sets?
- If the participant maintains the exact 75% hit rate from Trial Set 1, what minimum trial count n is required to reject H0 at alpha = 0.05?
Similar questions
- Orthogonal OLS Precision, Live Sharpe Decay, and L1 Optimal Prediction
- Sliding-Window Mean With IEEE-754 Infinities and NaNs
- How K-Fold Cross-Validation Affects Bias, Variance, and Test Errors
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times
- Target Bankroll Probability with Biased Flips