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:
exact_tail(P(X > threshold)): The exact probability of observing strictly more thanthresholdevents underBinomial(n, p), evaluated via the complement1 - sum_{k=0..threshold} C(n, k) * p^k * (1 - p)^(n - k).poisson_tail(P(Y > threshold)): The corresponding strict upper-tail probability underPoisson(lam)withlam = n * p, evaluated via1 - 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^70.0 <= p <= 1.0thresholdis an integer (may be negative,0, or>= n, withthreshold <= 10^5).- Return
[exact_tail, poisson_tail]as twofloatvalues in[0.0, 1.0].
Step-by-step walkthrough
Understand the two models we are comparing
Suppose a batch contains
nindependent network frames, and each frame experiences a bit-error event with probabilityp. LetXdenote the total count of corrupted frames in the batch:- Exact model (
X ~ Binomial(n, p)): Its probability mass function (PMF) — the formula giving the exact probability of observingkevents — isP(X = k) = C(n, k) * p^k * (1 - p)^(n - k)fork = 0, 1, ..., n. - Rare-event model (
Y ~ Poisson(lam)): Whennis large andpis very small,Binomial(n, p)converges toward a Poisson distribution with mean ratelam = n * pand PMFP(Y = k) = (lam^k * e^(-lam)) / k!fork = 0, 1, 2, ....
Given
n,p, andthreshold,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 islam = 8000 * 0.00025 = 2.0.- Exact model (
Turn an upper tail into a short sum with the complement rule
Summing
P(X > 3)directly from the right requires7,997terms (k = 4through8,000) for the Binomial distribution and infinitely many terms (k = 4, 5, 6, ...) for the Poisson distribution.Because probabilities across all
k >= 0add up to1, 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 than3events" excludes3, sok = 3belongs insideP(X <= 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:- Overflow (
> 1.8e308): Standard 64-bit floats top out around1.8e308. Atn = 2000, k = 1000,comb(2000, 1000)is roughly2.0e600, so converting or multiplying it in float64 raisesOverflowError. Similarly,lam ** kandfactorial(k)overflow pastk ≈ 171. - Underflow (
< 5e-324rounds to0.0): Even if you avoid factorials by starting atP(X = 0) = (1 - p) ** nand multiplying step-by-step ratios,(0.5) ** 2000rounds down to exact0.0in float64! Every subsequent term multiplied from0.0stays0.0, leavingcdf_sum = 0.0and returning a bogus1.0tail 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.3instead of0.0), advancelog_probby addition, and callexp(log_prob)only when adding each term intocdf_sum.- Overflow (
Derive the step-by-step log recurrence
Divide
P(X = k)by the preceding termP(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'smath.log1p(-p), which evaluateslog(1 + (-p))directly to full 16-digit precision even whenpis tiny (whereas1.0 - ploses low-order digits ofpfirst).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 return0.0. - For Binomial, check
if threshold >= n: return 1.0before checkingp == 1.0: whenp == 1.0,Xalways equalsn, soP(X <= threshold)is1.0ifthreshold >= nand0.0only whenthreshold < n. - When
p == 0.0(orlam == 0.0for Poisson) andthreshold >= 0, the count is deterministically0, so the CDF is1.0. - Clamping with
min(1.0, cdf_sum)guards against tiny floating-point rounding such as1.0000000000000002, ensuring1.0 - cdfis 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)- If
Trace Example 1 step by step
With
n = 8000,p = 0.00025,threshold = 3, we havelam = 2.0ande^(-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.1428765395Notice 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 largerp = 0.25creates a visible gap (0.050781vs0.080301).Error guarantee via Le Cam's inequality
Le Cam's inequality bounds the worst-case gap between
Binomial(n, p)andPoisson(n * p)at every cutofft:|P(X > t) - P(Y > t)| <= d_TV(Binomial(n, p), Poisson(n * p)) <= n * p^2 = lam * pHere
d_TVdenotes the total variation distance (the largest absolute probability difference between two distributions over any event):- At
n = 8,000andp = 0.00025(lam = 2.0): The gap cannot exceed8000 * (0.00025)^2 = 0.0005(and atthreshold = 3it is only~2.26e-5). - Scaling
nup to800,000while holdinglam = 2.0fixed (p = 0.0000025): Becausen * p^2 = lam^2 / n, multiplyingnby100shrinks the error ceiling 100-fold down to4 / 800,000 = 0.000005. - Takeaway: A small per-trial rate
p(solam * pis tiny) is what makes the Poisson approximation sharp.
- At
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)(specificallyO(min(threshold, n))forbinomial_cdfsincethreshold >= nreturns inO(1), plusO(max(0, threshold))forpoisson_cdf). Each step performsO(1)scalar math (logandexp) independent ofn, so scalingnfrom8,000to800,000takes identical runtime. - Space:
O(1). Both helpers keep only scalar floats (log_probandcdf_sum), allocating no arrays.
Edge cases
threshold < 0(e.g.,-1): Neither non-negative count can be<= -1, so both CDFs return0.0and both upper tails return1.0.threshold >= n: A Binomial count out ofntrials can never exceedn, soexact_tail = 0.0; meanwhile a Poisson count has no upper bound (k = 0, 1, 2, ...), sopoisson_tailremains strictly positive.- Degenerate
p = 0.0orp = 1.0: Handled explicitly before callinglog(p)orlog1p(-p). Checkingthreshold >= nbeforep == 1.0ensures thatp = 1.0withthreshold = nreturnsP(X <= n) = 1.0(exact_tail = 0.0). - Large mean (
n = 2000, p = 0.5, threshold = 1000): Both0.5^2000ande^(-1000)underflow to0.0in float64, yetlog_probstarts cleanly at-1386.29and-1000.0, climbing near0aroundk = 1000to produce the accurate~0.491tail. - Extreme upper tails (
P(X > threshold) < 1e-16): Subtracting1.0 - cdf_sumsuffers catastrophic cancellation (losing significant digits whencdf_sumrounds to1.0). When tiny probabilities below1e-16are required, sum upper termsk = threshold + 1, threshold + 2, ...directly until terms become negligible rather than using1 - CDF.
Common mistakes
- Off-by-one on strict
>:P(X > 3) = 1 - P(X <= 3)must includek = 3in the subtracted sum (range(1, threshold + 1)). Stopping atk = 2computesP(X >= 3)instead. - Computing
comb(n, k)orfactorial(k)directly with floats: RaisesOverflowErroroncecomb(n, k)ork!exceeds~1.8e308. - Running the ratio recurrence without logarithms: Avoids overflow, yet whenever
lam > 745,exp(-lam)underflows to0.0and zeroes out every subsequent term. - Writing
log(1.0 - p)instead oflog1p(-p): For tinyp(such asp = 1e-13),1.0 - ploses trailing precision beforelogis evaluated. - Assuming moderate
n * palone guarantees a good Poisson fit: By Le Cam's inequality (which bounds the maximum probability discrepancy betweenBinomial(n, p)andPoisson(n * p)byn * p^2 = lam * p),pitself must be small — in Example 2 (n = 4, p = 0.25),lam = 1.0is small, yetP(X > 2)is0.0508versus0.0803underPoisson(1.0).
Alternative approaches
- Per-term
math.lgamma(log(k!) = lgamma(k + 1)): Evaluating each term independently vialgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1)also avoids overflow and underflow. However, for very largen(e.g.,n = 10^9), subtracting two huge quantitieslgamma(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)andscipy.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)andPoisson(n * p)scales proportionally withp. Holdinglam = 3fixed (n = 20, p = 0.15), the total variation distance (the largest gap|P(X in A) - P(Y in A)|over any eventA) grows from~10^-5to several percentage points (P(X > 2)is0.595exact versus0.577Poisson). Holdingn = 8,000fixed (p = 0.15, solam = 1,200), Poisson overstates the variance (1,200versus Binomial'sn * p * (1 - p) = 1,020) and inflates upper tails (P(X > 1250)is0.0732Poisson versus0.0575exact, ~27% too high); in that large-mean regime, a continuity-correctedNormal(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), causingPoisson(lam)to severely understate burst tail probabilities — for example, if failures always arrive in simultaneous pairs at rate1.0per batch, the mean is still2.0while the variance doubles to4.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 isn * p * (1 - p)and the Poisson variance isn * p, giving a variance ratio of1 - p. Atp = 0.00025(n = 8,000),1 - p = 0.99975(1.9995versus2.0000), so their spreads are almost indistinguishable. Becausen * p > n * p * (1 - p)wheneverp > 0, the Poisson approximation is always slightly wider than the exact Binomial, placing slightly more probability mass in both outer tails (k = 0and largek) aspincreases.
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?
- Would a simple Poisson model remain valid if failures arrived in correlated bursts rather than independently, and what model would you use instead?
- How do the variances of Binomial(n, p) and Poisson(n * p) differ, and how does that discrepancy shape the tails?
Similar questions
- Continuity-Corrected Normal Estimate for Binomial Upper Tails
- Calendar Collision Thresholds and Circular Minimum Spacings
- Continuous vs. Block Coin Tossing for a Run of Heads
- Probability of Collecting At Least Two Red Balls
- Drawing Three Kept Balls with Green Replacements
- Winner Detection for a Connect Four Move Sequence
More Virtu Financial interview questions
- Continuity-Corrected Normal Estimate for Binomial Upper Tails Hard
- Calendar Collision Thresholds and Circular Minimum Spacings Hard
- Continuous vs. Block Coin Tossing for a Run of Heads Hard Pro
- Drawing Three Kept Balls with Green Replacements Medium Pro
- Winner Detection for a Connect Four Move Sequence Medium Pro
- Largest Triangle-Free Simple Graph Construction Hard Pro
- Peak-Shaped Skyline With Largest Combined Height Hard Pro
- Fewest Payments Needed to Clear Group Balances Hard Pro
- Coordinate Pair Reachability Under Sum Updates Hard Pro
- Probability of Collecting At Least Two Red Balls Medium Pro