Exact and Poisson Tail Probabilities for Rare Trials

Hard · Statistics & Math · Quantitative Researcher · Onsite

Problem Statement

Implement rare_event_binomial_probability(n, p, threshold) to compare the exact Binomial upper-tail probability against its rare-event Poisson approximation when n independent trials each trigger an event with probability p.

Let X ~ Binomial(n, p) denote the exact count of events across the n trials, and let Y ~ Poisson(lam) with matched mean lam = n * p denote the Poisson count approximation. Return a two-element list [exact_tail, poisson_tail] of floats:

  1. exact_tail (P(X > threshold)): The exact probability of observing strictly more than threshold events under Binomial(n, p), evaluated via the complement 1 - sum_{k=0..threshold} C(n, k) * p^k * (1 - p)^(n - k).
  2. poisson_tail (P(Y > threshold)): The corresponding strict upper-tail probability under Poisson(lam) with lam = n * p, evaluated via 1 - sum_{k=0..threshold} (lam^k * e^(-lam)) / k!.

Handle boundary and numerical cases cleanly: - When threshold < 0, every non-negative count exceeds threshold, so both entries equal 1.0. - When threshold >= n, X can never exceed n (exact_tail = 0.0), whereas Y remains unbounded above so poisson_tail is still computed from Poisson(lam). - Degenerate rates p == 0.0 (X = 0, Y = 0) and p == 1.0 (X = n, Y ~ Poisson(n)) must not raise math domain errors, and large n or large n * p must not overflow factorials or underflow (1 - p)^n / e^(-lam).

Examples

Example 1

Input: n = 8000, p = 0.00025, threshold = 3
Output: [0.14285397845080006, 0.14287653950145285]

Across 8000 frames with per-frame error rate 0.00025, the expected count is lam = 2.0. Summing k = 0, 1, 2, 3 gives P(X <= 3) ≈ 0.857146 (exact_tail ≈ 0.142854) and P(Y <= 3) = (19 / 3) * e^(-2) ≈ 0.857123 (poisson_tail ≈ 0.142877), differing by roughly 2.3e-5.

Example 2

Input: n = 4, p = 0.25, threshold = 2
Output: [0.05078125, 0.08030139707139416]

With only 4 trials and a non-rare p = 0.25 (lam = 1.0), exact P(X > 2) = P(X = 3) + P(X = 4) = 13 / 256 = 0.05078125, whereas Poisson(1.0) gives 1 - 2.5 * e^(-1) ≈ 0.080301 because p is no longer small.

Constraints

  • 1 <= n <= 10^7
  • 0.0 <= p <= 1.0
  • threshold is an integer (may be negative, 0, or >= n, with threshold <= 10^5).
  • Return [exact_tail, poisson_tail] as two float values in [0.0, 1.0].

Step-by-step walkthrough

  1. Understand the two models we are comparing

    Suppose a batch contains n independent network frames, and each frame experiences a bit-error event with probability p. Let X denote the total count of corrupted frames in the batch:

    1. Exact model (X ~ Binomial(n, p)): Its probability mass function (PMF) — the formula giving the exact probability of observing k events — is P(X = k) = C(n, k) * p^k * (1 - p)^(n - k) for k = 0, 1, ..., n.
    2. Rare-event model (Y ~ Poisson(lam)): When n is large and p is very small, Binomial(n, p) converges toward a Poisson distribution with mean rate lam = n * p and PMF P(Y = k) = (lam^k * e^(-lam)) / k! for k = 0, 1, 2, ....

    Given n, p, and threshold, rare_event_binomial_probability(n, p, threshold) returns [P(X > threshold), P(Y > threshold)]. In Example 1 (n = 8000, p = 0.00025, threshold = 3), the mean rate is lam = 8000 * 0.00025 = 2.0.

  2. Turn an upper tail into a short sum with the complement rule

    Summing P(X > 3) directly from the right requires 7,997 terms (k = 4 through 8,000) for the Binomial distribution and infinitely many terms (k = 4, 5, 6, ...) for the Poisson distribution.

    Because probabilities across all k >= 0 add up to 1, the complement rule converts an upper tail into a short lower-tail sum:

    All counts:    0   1   2   3 |  4   5   6  ...
                  \_____________/ \______________/
                   P(X <= 3): 4       P(X > 3)
    
    P(X > threshold) = 1 - P(X <= threshold)
                     = 1 - [P(X = 0) + P(X = 1) + ... + P(X = threshold)]
    

    Watch the strict > sign carefully: "strictly more than 3 events" excludes 3, so k = 3 belongs inside P(X <= 3)!

  3. Why textbook factorials and powers break in floating point

    Writing comb(n, k) * (p ** k) * ((1 - p) ** (n - k)) or (lam ** k) * exp(-lam) / factorial(k) works on tiny numbers, yet fails on valid larger inputs:

    1. Overflow (> 1.8e308): Standard 64-bit floats top out around 1.8e308. At n = 2000, k = 1000, comb(2000, 1000) is roughly 2.0e600, so converting or multiplying it in float64 raises OverflowError. Similarly, lam ** k and factorial(k) overflow past k ≈ 171.
    2. Underflow (< 5e-324 rounds to 0.0): Even if you avoid factorials by starting at P(X = 0) = (1 - p) ** n and multiplying step-by-step ratios, (0.5) ** 2000 rounds down to exact 0.0 in float64! Every subsequent term multiplied from 0.0 stays 0.0, leaving cdf_sum = 0.0 and returning a bogus 1.0 tail instead of ~0.491.

    The clean remedy for both failure modes is working in log space: maintain log_prob = log P(X = k) (a modest negative float such as -1386.3 instead of 0.0), advance log_prob by addition, and call exp(log_prob) only when adding each term into cdf_sum.

  4. Derive the step-by-step log recurrence

    Divide P(X = k) by the preceding term P(X = k - 1) so all factorials cancel down to a single fraction:

    1) Binomial combinations cancel down to one fraction:
       C(n, k)       n! / (k! * (n - k)!)       (n - k + 1)!   (k - 1)!     n - k + 1
       ---------  =  ------------------------ = ------------ * --------  =  ---------
       C(n, k-1)     n! / ((k-1)! * (n-k+1)!)     (n - k)!        k!            k
    
    2) Binomial probability powers cancel to p / (1 - p):
       [p^k * (1 - p)^(n - k)] / [p^(k - 1) * (1 - p)^(n - k + 1)]  =  p / (1 - p)
    
       ==>  P(X = k) / P(X = k - 1)  =  ((n - k + 1) / k) * (p / (1 - p))
       ==>  log P(X = k)  =  log P(X = k - 1) + log((n - k + 1) / k) + log(p) - log(1 - p)
    
    3) Poisson terms cancel even more simply:
       P(Y = k) / P(Y = k - 1)  =  [lam^k * e^-lam / k!] / [lam^(k-1) * e^-lam / (k-1)!]
                                =  lam / k
       ==>  log P(Y = k)  =  log P(Y = k - 1) + log(lam / k)
    

    For log(1 - p), call Python's math.log1p(-p), which evaluates log(1 + (-p)) directly to full 16-digit precision even when p is tiny (whereas 1.0 - p loses low-order digits of p first).

  5. Code the exact Binomial CDF and Poisson CDF

    Before taking logarithms, handle boundary inputs where the answer is immediate or log(0) would be undefined:

    • If threshold < 0, no non-negative count can satisfy <= threshold, so both CDFs return 0.0.
    • For Binomial, check if threshold >= n: return 1.0 before checking p == 1.0: when p == 1.0, X always equals n, so P(X <= threshold) is 1.0 if threshold >= n and 0.0 only when threshold < n.
    • When p == 0.0 (or lam == 0.0 for Poisson) and threshold >= 0, the count is deterministically 0, so the CDF is 1.0.
    • Clamping with min(1.0, cdf_sum) guards against tiny floating-point rounding such as 1.0000000000000002, ensuring 1.0 - cdf is never negative.
    from math import exp, log, log1p
    
    
    def binomial_cdf(n: int, p: float, threshold: int) -> float:
        """Return P(X <= threshold) for X ~ Binomial(n, p)."""
        # Phase 1: Handle boundary thresholds and degenerate probabilities (p == 0 or p == 1)
        # where log(p) or log(1 - p) would be undefined.
        if threshold < 0:
            return 0.0
        # Check threshold >= n BEFORE p == 1.0: when p == 1.0, X is always n, so P(X <= n) is 1.0.
        if threshold >= n:
            return 1.0
        if p == 0.0:
            return 1.0  # X is deterministically 0, and threshold >= 0
        if p == 1.0:
            return 0.0  # X is deterministically n, and threshold < n
    
        # Phase 2: Accumulate P(X = 0) + ... + P(X = threshold) via a log-space recurrence
        # so (1 - p)^n never underflows to 0.0 and comb(n, k) never overflows float64.
        # log_prob stores log P(X = k), starting at k = 0: log((1 - p)^n) = n * log(1 - p).
        log_prob = n * log1p(-p)
        log_odds = log(p) - log1p(-p)  # log(p / (1 - p)), added once per step
        cdf_sum = exp(log_prob)
    
        for k in range(1, threshold + 1):
            # Ratio identity: P(X = k) / P(X = k - 1) = ((n - k + 1) / k) * (p / (1 - p)).
            log_prob += log((n - k + 1) / k) + log_odds
            cdf_sum += exp(log_prob)
    
        # Clamp to 1.0 so tiny float rounding above 1.0 never makes 1.0 - cdf_sum negative.
        return min(1.0, cdf_sum)
    
    
    def poisson_cdf(lam: float, threshold: int) -> float:
        """Return P(Y <= threshold) for Y ~ Poisson(lam)."""
        if threshold < 0:
            return 0.0
        if lam == 0.0:
            return 1.0  # Y is deterministically 0, and threshold >= 0
    
        # log_prob stores log P(Y = k), starting at k = 0: log(e^-lam) = -lam.
        log_prob = -lam
        cdf_sum = exp(log_prob)
    
        for k in range(1, threshold + 1):
            # Ratio identity: P(Y = k) / P(Y = k - 1) = lam / k.
            log_prob += log(lam / k)
            cdf_sum += exp(log_prob)
    
        return min(1.0, cdf_sum)
    
  6. Trace Example 1 step by step

    With n = 8000, p = 0.00025, threshold = 3, we have lam = 2.0 and e^(-2) ≈ 0.13533528:

     k | Binomial P(X = k) | Poisson P(Y = k)  | Running Poisson CDF
    ---+-------------------+-------------------+--------------------
     0 |     0.13530145    |     0.13533528    |      0.13533528
     1 |     0.27067056    |     0.27067057    |      0.40600585
     2 |     0.27070441    |     0.27067057    |      0.67667642
     3 |     0.18046960    |     0.18044704    |      0.85712346
    
    Exact Binomial P(X > 3) = 1 - 0.8571460215 = 0.1428539785
    Poisson approx P(Y > 3) = 1 - 0.8571234605 = 0.1428765395
    

    Notice how closely the two columns track each other (gap ≈ 2.26e-5), whereas in Example 2 (n = 4, p = 0.25, threshold = 2) the much larger p = 0.25 creates a visible gap (0.050781 vs 0.080301).

  7. Error guarantee via Le Cam's inequality

    Le Cam's inequality bounds the worst-case gap between Binomial(n, p) and Poisson(n * p) at every cutoff t:

    |P(X > t) - P(Y > t)|  <=  d_TV(Binomial(n, p), Poisson(n * p))  <=  n * p^2  =  lam * p
    

    Here d_TV denotes the total variation distance (the largest absolute probability difference between two distributions over any event):

    • At n = 8,000 and p = 0.00025 (lam = 2.0): The gap cannot exceed 8000 * (0.00025)^2 = 0.0005 (and at threshold = 3 it is only ~2.26e-5).
    • Scaling n up to 800,000 while holding lam = 2.0 fixed (p = 0.0000025): Because n * p^2 = lam^2 / n, multiplying n by 100 shrinks the error ceiling 100-fold down to 4 / 800,000 = 0.000005.
    • Takeaway: A small per-trial rate p (so lam * p is tiny) is what makes the Poisson approximation sharp.
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from math import exp, log, log1p
    
    
    def binomial_cdf(n: int, p: float, threshold: int) -> float:
        """Return P(X <= threshold) for X ~ Binomial(n, p)."""
        # Phase 1: Handle boundary thresholds and degenerate probabilities (p == 0 or p == 1)
        # where log(p) or log(1 - p) would be undefined.
        if threshold < 0:
            return 0.0
        # Check threshold >= n BEFORE p == 1.0: when p == 1.0, X is always n, so P(X <= n) is 1.0.
        if threshold >= n:
            return 1.0
        if p == 0.0:
            return 1.0  # X is deterministically 0, and threshold >= 0
        if p == 1.0:
            return 0.0  # X is deterministically n, and threshold < n
    
        # Phase 2: Accumulate P(X = 0) + ... + P(X = threshold) via a log-space recurrence
        # so (1 - p)^n never underflows to 0.0 and comb(n, k) never overflows float64.
        # log_prob stores log P(X = k), starting at k = 0: log((1 - p)^n) = n * log(1 - p).
        log_prob = n * log1p(-p)
        log_odds = log(p) - log1p(-p)  # log(p / (1 - p)), added once per step
        cdf_sum = exp(log_prob)
    
        for k in range(1, threshold + 1):
            # Ratio identity: P(X = k) / P(X = k - 1) = ((n - k + 1) / k) * (p / (1 - p)).
            log_prob += log((n - k + 1) / k) + log_odds
            cdf_sum += exp(log_prob)
    
        # Clamp to 1.0 so tiny float rounding above 1.0 never makes 1.0 - cdf_sum negative.
        return min(1.0, cdf_sum)
    
    
    def poisson_cdf(lam: float, threshold: int) -> float:
        """Return P(Y <= threshold) for Y ~ Poisson(lam)."""
        if threshold < 0:
            return 0.0
        if lam == 0.0:
            return 1.0  # Y is deterministically 0, and threshold >= 0
    
        # log_prob stores log P(Y = k), starting at k = 0: log(e^-lam) = -lam.
        log_prob = -lam
        cdf_sum = exp(log_prob)
    
        for k in range(1, threshold + 1):
            # Ratio identity: P(Y = k) / P(Y = k - 1) = lam / k.
            log_prob += log(lam / k)
            cdf_sum += exp(log_prob)
    
        return min(1.0, cdf_sum)
    
    
    def rare_event_binomial_probability(n: int, p: float, threshold: int) -> List[float]:
        # Expected event count lambda = n * p matches the Binomial and Poisson means.
        lam = n * p
        exact_tail = 1.0 - binomial_cdf(n, p, threshold)
        poisson_tail = 1.0 - poisson_cdf(lam, threshold)
        return [exact_tail, poisson_tail]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine monitoring a batch of 8,000 transmitted network frames where each frame independently has a tiny 0.00025 chance of suffering a bit error. Counting exact corruptions across those 8,000 slots follows the Binomial distribution (X ~ Binomial(n, p)), while treating errors as rare random arrivals at a steady average rate of lam = n * p = 2.0 per batch uses the Poisson distribution (a discrete count model for rare, independent events occurring at a constant average rate lam). Rather than summing 7,997 Binomial terms — or infinitely many Poisson terms — for 4, 5, 6, ... errors, we flip to the complement P(count > 3) = 1 - P(count <= 3) and sum just the 4 probabilities for 0, 1, 2, 3 errors, stepping from k - 1 to k in log space (updating log P by addition before exponentiating each term).

Evaluating textbook formulas like comb(n, k) * p^k * (1 - p)^(n - k) or lam^k * e^(-lam) / k! directly breaks down on larger inputs because factorials and powers overflow 64-bit floats (> 1.8e308). Even multiplying step-by-step ratios in plain floats fails when lam is large (such as n = 2000, p = 0.5), because the starting term P(X = 0) = (1 - p)^n suffers underflow (a positive value smaller than ~5e-324 rounding down to 0.0), zeroing out every term built from it.

Let's trace Example 1 (n = 8,000, p = 0.00025, threshold = 3, so lam = 2.0): - For Poisson, log_prob starts at -2.0 (P(Y = 0) = e^(-2) ≈ 0.13534), and for k = 1..3 adds log(2.0 / k) each step, yielding terms 0.27067, 0.27067, 0.18045. - Their sum is P(Y <= 3) ≈ 0.857123, giving 1 - P(Y <= 3) ≈ 0.142877. - The Binomial log recurrence starts at 8000 * log1p(-0.00025) and sums k = 0..3 to 0.857146, giving 1 - P(X <= 3) ≈ 0.142854.

Complexity

  • Time: O(threshold) (specifically O(min(threshold, n)) for binomial_cdf since threshold >= n returns in O(1), plus O(max(0, threshold)) for poisson_cdf). Each step performs O(1) scalar math (log and exp) independent of n, so scaling n from 8,000 to 800,000 takes identical runtime.
  • Space: O(1). Both helpers keep only scalar floats (log_prob and cdf_sum), allocating no arrays.

Edge cases

  • threshold < 0 (e.g., -1): Neither non-negative count can be <= -1, so both CDFs return 0.0 and both upper tails return 1.0.
  • threshold >= n: A Binomial count out of n trials can never exceed n, so exact_tail = 0.0; meanwhile a Poisson count has no upper bound (k = 0, 1, 2, ...), so poisson_tail remains strictly positive.
  • Degenerate p = 0.0 or p = 1.0: Handled explicitly before calling log(p) or log1p(-p). Checking threshold >= n before p == 1.0 ensures that p = 1.0 with threshold = n returns P(X <= n) = 1.0 (exact_tail = 0.0).
  • Large mean (n = 2000, p = 0.5, threshold = 1000): Both 0.5^2000 and e^(-1000) underflow to 0.0 in float64, yet log_prob starts cleanly at -1386.29 and -1000.0, climbing near 0 around k = 1000 to produce the accurate ~0.491 tail.
  • Extreme upper tails (P(X > threshold) < 1e-16): Subtracting 1.0 - cdf_sum suffers catastrophic cancellation (losing significant digits when cdf_sum rounds to 1.0). When tiny probabilities below 1e-16 are required, sum upper terms k = threshold + 1, threshold + 2, ... directly until terms become negligible rather than using 1 - CDF.

Common mistakes

  • Off-by-one on strict >: P(X > 3) = 1 - P(X <= 3) must include k = 3 in the subtracted sum (range(1, threshold + 1)). Stopping at k = 2 computes P(X >= 3) instead.
  • Computing comb(n, k) or factorial(k) directly with floats: Raises OverflowError once comb(n, k) or k! exceeds ~1.8e308.
  • Running the ratio recurrence without logarithms: Avoids overflow, yet whenever lam > 745, exp(-lam) underflows to 0.0 and zeroes out every subsequent term.
  • Writing log(1.0 - p) instead of log1p(-p): For tiny p (such as p = 1e-13), 1.0 - p loses trailing precision before log is evaluated.
  • Assuming moderate n * p alone guarantees a good Poisson fit: By Le Cam's inequality (which bounds the maximum probability discrepancy between Binomial(n, p) and Poisson(n * p) by n * p^2 = lam * p), p itself must be small — in Example 2 (n = 4, p = 0.25), lam = 1.0 is small, yet P(X > 2) is 0.0508 versus 0.0803 under Poisson(1.0).

Alternative approaches

  • Per-term math.lgamma (log(k!) = lgamma(k + 1)): Evaluating each term independently via lgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1) also avoids overflow and underflow. However, for very large n (e.g., n = 10^9), subtracting two huge quantities lgamma(n + 1) - lgamma(n - k + 1) loses floating-point precision, whereas our step-by-step ratio recurrence stays accurate.
  • Scientific library survival functions: Where third-party libraries are allowed, scipy.stats.binom.sf(threshold, n, p) and scipy.stats.poisson.sf(threshold, n * p) use regularized incomplete beta and gamma functions to evaluate upper tails directly without cancellation in far tails.

Follow-up questions

  • What happens to the Poisson tail error when the per-trial event probability rises to a moderate level like p = 0.15? The approximation degrades substantially because the discrepancy between Binomial(n, p) and Poisson(n * p) scales proportionally with p. Holding lam = 3 fixed (n = 20, p = 0.15), the total variation distance (the largest gap |P(X in A) - P(Y in A)| over any event A) grows from ~10^-5 to several percentage points (P(X > 2) is 0.595 exact versus 0.577 Poisson). Holding n = 8,000 fixed (p = 0.15, so lam = 1,200), Poisson overstates the variance (1,200 versus Binomial's n * p * (1 - p) = 1,020) and inflates upper tails (P(X > 1250) is 0.0732 Poisson versus 0.0575 exact, ~27% too high); in that large-mean regime, a continuity-corrected Normal(1200, 1020) approximation is far more accurate.
  • Would a simple Poisson model remain valid if failures arrived in correlated bursts rather than independently, and what model would you use instead? No, standard Poisson fails because its derivation requires events to arrive singly and independently without contagion. Correlated bursts produce overdispersion (variance strictly exceeding the mean, whereas a plain Poisson distribution forces variance == mean), causing Poisson(lam) to severely understate burst tail probabilities — for example, if failures always arrive in simultaneous pairs at rate 1.0 per batch, the mean is still 2.0 while the variance doubles to 4.0. Appropriate replacements include a compound Poisson distribution (a Poisson number of burst arrivals, each carrying a random burst size), a Negative Binomial count model, or a self-exciting Hawkes process.
  • How do the variances of Binomial(n, p) and Poisson(n * p) differ, and how does that discrepancy shape the tails? Both models share the exact same mean n * p, whereas the Binomial variance is n * p * (1 - p) and the Poisson variance is n * p, giving a variance ratio of 1 - p. At p = 0.00025 (n = 8,000), 1 - p = 0.99975 (1.9995 versus 2.0000), so their spreads are almost indistinguishable. Because n * p > n * p * (1 - p) whenever p > 0, the Poisson approximation is always slightly wider than the exact Binomial, placing slightly more probability mass in both outer tails (k = 0 and large k) as p increases.

Follow-up questions

Similar questions

More Virtu Financial interview questions

All 13 Virtu Financial questions →