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 = 4 draws, k = 3 correct (75.0% apparent accuracy).
  • Trial Set 2: n = 48 draws, k = 24 correct (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):

  1. Hypothesis & Modeling Context: Under H0: p = p0 against the directional alternative H1: 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 level alpha = 0.05 (as well as comparison against a continuity-corrected normal approximation when n * p and n * (1 - p) are large).
  2. Boundary & Validation Rules:
    • Raise ValueError if n < 0 or if p is outside [0.0, 1.0] (including NaN).
    • Return 1.0 whenever k <= 0, and return 0.0 whenever k > n (including when n == 0).
    • Handle degenerate probabilities p == 0.0 and p == 1.0 cleanly without domain errors.
    • Maintain numerical accuracy for large n (where C(n, j) overflows 64-bit floats), tiny p, and extreme upper tails (where 1.0 - P(X < k) loses precision to catastrophic cancellation).

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 to 10^4; negative n must raise ValueError).
  • k can be any integer, including k <= 0 and k > n.
  • 0.0 <= p <= 1.0 (values outside [0.0, 1.0] or NaN must raise ValueError).
  • Returned probabilities must lie in [0.0, 1.0] and preserve relative precision even when the exact tail is far below 10^-16.

Step-by-step walkthrough

  1. 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 = 3 hits in n = 4 attempts) and Trial Set 2 (k = 24 hits in n = 48 attempts)—and implement exact_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 + 1 possible hit counts 0, 1, ..., n, the one-sided p-value adds up the shaded upper tail from k through n:

    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-4
    

    Once exact_binomial_upper_tail is built, Trial Set 1 is exact_binomial_upper_tail(4, 3, 0.25) and Trial Set 2 is exact_binomial_upper_tail(48, 24, 0.25). Let us walk through the statistical framing first, then build a numerically safe log-space implementation.

  2. Formulate the hypothesis test and binomial assumptions

    Let p be 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; equivalently p <= 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 follows Binomial(n, 0.25) when five assumptions hold:

    1. Pre-specified trial count (n): n = 4 and n = 48 are fixed before observing outcomes rather than halting as soon as a streak looks impressive (optional stopping inflates Type I error).
    2. Binary outcomes: Every draw produces either a hit (1) or a miss (0).
    3. 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.
    4. Identical success probability (p = 0.25): Because all 4 suits have probability 1/4 on every draw, any guessing strategy without genuine signal succeeds with probability 1/4 each time.
    5. Sensory blinding: Physical cues (bent corners, card markings, dealer reactions) cannot leak the suit.
  3. Compute Trial Set 1 by hand

    The binomial probability mass function (PMF) gives the exact probability of observing j hits in n trials: P(X = j) = C(n, j) * p^j * (1 - p)^(n - j), where C(n, j) = n! / (j! * (n - j)!) counts how many subsets of j trials can be the hits, p^j is the probability of those j hits, and (1 - p)^(n - j) is the probability of the n - j misses.

    For Trial Set 1 (n = 4, k = 3, p = 0.25), "at least 3 hits" means X = 3 or X = 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.05078125
    

    At significance threshold alpha = 0.05, 0.05078125 > 0.05, so we fail to reject H0. Pure luck alone scores 3 or 4 out of 4 roughly once every 20 sessions (5.08%). With n = 4, only a perfect 4 / 4 (p = 1 / 256 ≈ 0.0039) crosses alpha = 0.05.

  4. Approximate and verify Trial Set 2

    For Trial Set 2 (n = 48, k = 24, p = 0.25), under H0 the expected hit count is mean = n * p = 12 and the standard deviation is sd = sqrt(n * p * (1 - p)) = sqrt(48 * 0.25 * 0.75) = sqrt(9) = 3. Because both n * p = 12 >= 10 and n * (1 - p) = 36 >= 10, a normal curve Normal(mean = 12, sd = 3) approximates the center well.

    When approximating discrete integer counts with a continuous density, integer m spans [m - 0.5, m + 0.5). A continuity correction shifts the cutoff from 24 down to 23.5 so the continuous integral captures the full probability bar centered at 24:

    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-4
    

    All three figures lie far below alpha = 0.05, so we strongly reject H0. Notice that even after continuity correction, the symmetric normal tail still underestimates the exact binomial tail by about 2.6x because p = 0.25 < 0.50 skews Binomial(48, 0.25) positively to the right.

  5. 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 H0
    

    Trial Set 1 exhibits double the effect size (+50.0 vs. +25.0 percentage points above chance), yet misses significance because the standard error (sqrt(p * (1 - p) / n)) shrinks at rate 1 / sqrt(n). At n = 4, sampling noise easily swings accuracy by +/-21.7 percentage points; at n = 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.

  6. 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:

    1. Integer-to-float overflow: At n = 2000, j = 1000, C(2000, 1000) is roughly 10^601, exceeding the 64-bit float ceiling (~1.8e308) and raising OverflowError.
    2. Power underflow: At n = 5000, j = 1250, p = 0.25, 0.25 ** 1250 underflows straight to 0.0 even though P(X = 1250) is around 0.013.
    3. Catastrophic cancellation from 1 - lower_tail: For n = 100, k = 90, p = 0.2, the true upper tail is ~2.37e-51, whereas 1.0 - P(X <= 89) subtracts a value indistinguishable from 1.0 in 53-bit float precision (ulp ~1.1e-16), wiping out every significant digit.

    Summing the upper tail j = k..n directly 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) computes ln(m!) in O(1) time without constructing huge integers, math.log1p(-p) preserves accuracy when p is near 0, and math.fsum sums 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-circuit p == 0.0 or p == 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
    
  7. 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)). After O(1) validation and boundary checks, the loop visits each integer hit count j from k to n once, calling O(1) math functions (lgamma, log, log1p, exp) per step, followed by one linear math.fsum pass over the n - k + 1 terms.
  • Space: O(n - k + 1) for the tail_probabilities list passed into math.fsum (reducible to O(1) with a running float sum if memory is constrained, at a minor cost in rounding accuracy).

Edge cases

  • k <= 0: Since a binomial count X is always non-negative, X >= k holds with probability 1.0—including n = 0, k = 0.
  • k > n: Scoring more hits than attempts is impossible (0.0), including n = 0, k = 1.
  • p = 0.0 or p = 1.0: Returning before binomial_log_pmf avoids math.log(0) (ValueError) and handles deterministic outcomes cleanly (X = 0 when p = 0, X = n when p = 1).
  • Extreme upper tails (k close to n): Direct summation over j = k..n retains full relative precision even around 10^-51, where 1 - P(X < k) rounds to 0.0.
  • Large n (n = 2000+): math.lgamma avoids converting 600+-digit integers to 64-bit floats.
  • Invalid inputs (n < 0, p < 0, p > 1, or p = NaN): Rejected immediately with ValueError.

Common mistakes

  • Computing P(X > k) instead of P(X >= k). By definition, a one-sided p-value includes the observed count k ("at least as extreme as observed"), so Example 1 adds j = 3 and j = 4, not j = 4 alone.
  • 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 24 covers [23.5, 24.5) on the continuous line, so Y >= 24 starts at 23.5 (z = (23.5 - 12) / 3 = 3.833), whereas 24.5 approximates Y >= 25.
  • Applying a normal approximation to tiny n or trusting it deep in a skewed tail. At n = 4, p = 0.25, np = 1.0 violates np >= 10; even at n = 48, right-skewness makes the exact tail ~2.6 times larger than the continuity-corrected normal tail at z ≈ 3.83.
  • Confusing the p-value with P(H0 is true) or raw effect size. A p-value is P(X >= k | H0), not the probability that the participant is guessing; conversely, 75.0% on n = 4 provides weaker evidence than 50.0% on n = 48.

Alternative approaches

  • Multiplicative term recurrence: Using P(X = j + 1) = P(X = j) * ((n - j) / (j + 1)) * (p / (1 - p)) avoids calling lgamma and exp on every iteration after computing the initial log-PMF at k (or at the mode floor((n + 1) * p) when P(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 the Beta(k, n - k + 1) density up to p, scientific libraries (scipy.stats.binom.sf(k - 1, n, p)) evaluate the tail via continued fractions in nearly O(1) time even for huge n.

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/4 success probability, and repeating one fixed suit in Trial Set 1 follows a hypergeometric distribution (the exact count distribution for sampling without replacement), giving P(X >= 3) = (C(4, 3) * C(12, 1) + C(4, 4)) / C(16, 4) = 49 / 1820 ≈ 0.0269 because 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 averages 6.73 hits per 16-card deck (20.20 across 48 draws), lifting Trial Set 2's p-value to P(Y >= 24) ≈ 0.0968 > 0.05 and 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, updating k hits and n - k misses directly to Beta(a + k, b + n - k) (a and b act like prior pseudo-hits and pseudo-misses). Starting from a flat Beta(1, 1) uniform prior, Trial Set 1 (3 / 4) yields Beta(4, 2) (mean 0.667, wide 95% credible interval [0.28, 0.95], heavily shaped by the prior's 75% mass above 0.25), whereas Trial Set 2 (24 / 48) yields Beta(25, 25) (mean 0.500, tight 95% credible interval [0.36, 0.64], P(p <= 0.25 | data) ≈ 8.03e-5, dominated by the 48 observations). Comparing H1: p ~ Beta(1, 1) against the sharp null H0: p = 0.25 via a Bayes factor—the ratio of marginal data likelihood under H1 versus H0—gives only ~4.27 for Trial Set 1 versus ~177.5 for 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 / n to equal 3/4 (75.0%) strictly with integer counts, n must be a multiple of 4. At n = 4 (k = 3), P(X >= 3 | n = 4, p = 0.25) = 13 / 256 ≈ 0.05078 > 0.05 just misses the cutoff; at the next multiple of 4, 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 / 8 correct) are required. Notice that a naive normal approximation (0.75 - 0.25) / sqrt(0.1875 / n) >= 1.645 yields n >= 2.03 -> 3, which fails at small n both because 3 cannot produce 75% and because n = 4 still exceeds 0.05.

Follow-up questions

Similar questions

More Headlands interview questions

All 4 Headlands questions →