Continuity-Corrected Normal Estimate for Binomial Upper Tails
Hard · Statistics & Math · Quantitative Researcher · Onsite
Problem Statement
Implement normal_approx_binomial_upper_tail(n, p, k) to estimate the strict upper-tail probability P(X > k) for a Binomial random variable X ~ Binomial(n, p) using a continuity-corrected Normal distribution.
Here X counts the total number of successes across n independent trials, each succeeding with probability p. Compute your estimate using these exact steps:
- Moment matching: Construct a Gaussian random variable
Ywhose meanmu = n * pand standard deviationsigma = sqrt(n * p * (1 - p))match those ofX. - Half-unit continuity shift: Because
Xtakes integer values, the strict eventX > kcorresponds toX >= k + 1. Treating each integerjas a unit-width histogram bar spanning[j - 0.5, j + 0.5], shift the cutoff fromkup tok + 0.5so barkis excluded completely. - Zero-variance edge case: Whenever
sigma == 0(which happens whenn == 0,p == 0.0, orp == 1.0),Xis deterministically equal tomu; return1.0ifmu > k + 0.5and0.0otherwise. - Standard Normal survival probability: When
sigma > 0, standardizez = (k + 0.5 - mu) / sigmaand returnP(Z > z) = 1 - Phi(z)forZ ~ Normal(0, 1)to standard 64-bit floating-point precision.
Examples
Example 1
Input: n = 64, p = 0.5, k = 38
Output: 0.052081279415219554
With 64 fair trials, mu = 64 * 0.5 = 32.0 and sigma = sqrt(64 * 0.25) = 4.0. Shifting k = 38 to 38.5 produces z = (38.5 - 32.0) / 4.0 = 1.625, whose upper-tail Normal area P(Z > 1.625) is approximately 0.052081 (closely tracking the exact Binomial value 0.051711).
Example 2
Input: n = 400, p = 0.2, k = 95
Output: 0.026342126689141463
Here mu = 400 * 0.2 = 80.0 and sigma = sqrt(400 * 0.2 * 0.8) = 8.0. Applying the +0.5 shift gives (95.5 - 80.0) / 8.0 = 1.9375, and P(Z > 1.9375) evaluates to approximately 0.026342.
Constraints
0 <= n <= 10^90.0 <= p <= 1.0kis an arbitrary integer (including values< 0or>= n).- Return the probability as a
floatin[0.0, 1.0].
Step-by-step walkthrough
Frame the Binomial-to-Normal approximation
Let
Xcount the number of successes acrossnindependent trials where each trial succeeds with probabilityp. We sayXfollows a Binomial distribution, writtenBinomial(n, p).Given
n,p, and an integerk, our functionnormal_approx_binomial_upper_tail(n, p, k)computes the continuity-corrected Normal approximation to the strict upper-tail probabilityP(X > k).Match the mean and standard deviation
Write
Xas the sum ofnindependent indicator variablesX = I_1 + I_2 + ... + I_n, where eachI_iequals1(probabilityp) or0(probability1 - p):- One trial has mean
pand variancep * (1 - p). - Across
nindependent trials, means add and variances add, yielding meanmu = n * pand variancesigma^2 = n * p * (1 - p). - Taking the square root gives the standard deviation
sigma = sqrt(n * p * (1 - p)), expressed in the same count units asX.
For Example 1 (
n = 64andp = 0.5):mean = n * p = 64 * 0.5 = 32.0 std_dev = sqrt(n * p * (1-p)) = sqrt(64 * 0.25) = 4.0By the Central Limit Theorem (which tells us that the sum of many independent trials approaches a smooth bell-shaped Gaussian curve),
Xis closely approximated byY ~ Normal(mean, std_dev^2)whenevern * p * (1 - p)is reasonably large. Always divide bystd_dev(4.0), never by the variance (16.0)!import math def _binomial_moments(n: int, p: float): mean = n * p std_dev = math.sqrt(n * p * (1.0 - p)) return mean, std_dev- One trial has mean
Continuity correction: why k shifts to k + 0.5
Xis discrete (it can equal38or39, never38.3), whereas the Normal distributionYis continuous (its probabilities come from area over intervals).Picture the Binomial probabilities as a histogram where each integer
jowns a unit-width bar centered atj, spanning[j - 0.5, j + 0.5]:bar 37 bar 38 bar 39 bar 40 [36.5..37.5] [37.5..38.5] [38.5..39.5] [39.5..40.5] +----------+ +----------+ +==========+ +==========+ | 37 | | 38 | # 39 # # 40 # ... -> P(X > 38) +----------+ +----------+ +==========+ +==========+ ^ boundary = 38.5 (k + 0.5) Discrete event Integer values Continuous Normal region -------------- -------------- ------------------------ P(X > k) k+1, k+2, ... P(Y > k + 0.5) P(X >= k) k, k+1, ... P(Y > k - 0.5) P(X <= k) ..., k-1, k P(Y <= k + 0.5) P(X < k) ..., k-2, k-1 P(Y <= k - 0.5)Because
X > 38meansX >= 39, we must exclude the entire bar for38and begin integrating under the Normal curve at the left edge of bar39, which sits at38.5(k + 0.5). Using38.0would wrongly include half of bar38; using37.5would include all of bar38(estimatingP(X >= 38)instead).Standardize to a z-score and compute the upper tail
To evaluate
P(Y > k + 0.5)forY ~ Normal(mean, std_dev^2), we convertk + 0.5into a z-score — how many standard deviations it lies from the mean:z_score = (corrected_boundary - mean) / std_devThen
P(Y > corrected_boundary) = P(Z > z_score) = 1 - Phi(z_score), whereZ ~ Normal(0, 1)is the standard Normal variable andPhi(z) = P(Z <= z)is its cumulative distribution function (CDF).In Python's
mathmodule, we evaluate1 - Phi(z)directly withmath.erfc, the complementary error function, via the exact identity:P(Z > z) = 1 - Phi(z) = 0.5 * erfc(z / sqrt(2))Why call
0.5 * math.erfc(...)rather than1.0 - Phi(z)? Whenzis large (sayz = 9),Phi(z)is so close to1that 64-bit floats roundPhi(z)to1.0, making1.0 - Phi(z)collapse to0.0instead of the true~1.1e-19. Callingerfccomputes the small upper tail directly without subtracting from1.0.We also guard against
std_dev == 0.0(whenp == 0,p == 1, orn == 0): in that degenerate caseXalways equalsmean, soP(X > k)is1.0whenmean > k + 0.5and0.0otherwise.def standard_normal_upper_tail(z: float) -> float: """Return P(Z > z) for a standard Normal random variable Z ~ Normal(0, 1).""" # Mathematically equal to 1 - Phi(z), where Phi is the standard Normal CDF. # Calling math.erfc directly avoids catastrophic cancellation when Phi(z) rounds to 1.0. return 0.5 * math.erfc(z / math.sqrt(2.0)) def normal_approx_binomial_upper_tail(n: int, p: float, k: int) -> float: """Approximate P(X > k) for X ~ Binomial(n, p) using a continuity-corrected Normal.""" # Phase 1: Match the Binomial mean (n * p) and standard deviation sqrt(n * p * (1 - p)). mean = n * p std_dev = math.sqrt(n * p * (1.0 - p)) # Phase 2: Continuity correction. # Since X is an integer, X > k is equivalent to X >= k + 1. In a unit-width histogram, # integer k occupies [k - 0.5, k + 0.5], so the region for k + 1, k + 2, ... starts at k + 0.5. corrected_boundary = k + 0.5 # Phase 3: Guard against zero variance (p == 0, p == 1, or n == 0), where X is constant # at `mean` and dividing by std_dev would raise ZeroDivisionError. if std_dev == 0.0: return 1.0 if mean > corrected_boundary else 0.0 # Phase 4: Standardize to a z-score (standard deviations from the mean) and evaluate P(Z > z). z_score = (corrected_boundary - mean) / std_dev return standard_normal_upper_tail(z_score)Walk through Example 1 (n = 64, p = 0.5, k = 38)
Plugging Example 1 into the four phases:
1. mean = 64 * 0.5 = 32.0 std_dev = sqrt(64 * 0.5 * 0.5) = 4.0 2. corrected_boundary = 38 + 0.5 = 38.5 3. z_score = (38.5 - 32.0) / 4.0 = 1.625 4. P(Z > 1.625) = 1 - Phi(1.625) = 1 - 0.947919 = 0.052081Compare all three boundary choices against the exact Binomial probabilities:
- With
+ 0.5(38.5,z = 1.625): gives0.052081, within0.00037(0.7%) of the exactP(X > 38) = 0.051711. - No correction (
38.0,z = 1.5): gives0.066807, overshooting0.051711by29%! - Wrong direction (
37.5,z = 1.375): gives0.084566, which approximatesP(X >= 38) = 0.084321instead.
- With
Why a small approximation error still remains
Even with continuity correction,
0.052081differs slightly from the exact0.051711for three reasons:- Smooth density vs staircase bars: Continuity correction matches the width of each integer bin, whereas a smooth Gaussian bell still differs slightly in curvature from flat-topped discrete bars.
- Finite
nand bounded support: Atp = 0.5,Binomial(64, 0.5)is completely symmetric (zero lopsidedness), eliminating skew error. However, the Binomial count cannot exceed64, making its outer tails slightly lighter than an unbounded Normal curve — so0.052081lands just above0.051711. - Relative error further into the tail: Central Limit Theorem guarantees control absolute CDF error (
~1 / sqrt(n)). When the true tail probability is small, a tiny absolute discrepancy translates into a larger relative percentage gap, especially whenp != 0.5introduces asymmetry (as in Example 2, where0.026342sits next to exact0.028300).
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import math def standard_normal_upper_tail(z: float) -> float: """Return P(Z > z) for a standard Normal random variable Z ~ Normal(0, 1).""" # Mathematically equal to 1 - Phi(z), where Phi is the standard Normal CDF. # Calling math.erfc directly avoids catastrophic cancellation when Phi(z) rounds to 1.0. return 0.5 * math.erfc(z / math.sqrt(2.0)) def normal_approx_binomial_upper_tail(n: int, p: float, k: int) -> float: """Approximate P(X > k) for X ~ Binomial(n, p) using a continuity-corrected Normal.""" # Phase 1: Match the Binomial mean (n * p) and standard deviation sqrt(n * p * (1 - p)). mean = n * p std_dev = math.sqrt(n * p * (1.0 - p)) # Phase 2: Continuity correction. # Since X is an integer, X > k is equivalent to X >= k + 1. In a unit-width histogram, # integer k occupies [k - 0.5, k + 0.5], so the region for k + 1, k + 2, ... starts at k + 0.5. corrected_boundary = k + 0.5 # Phase 3: Guard against zero variance (p == 0, p == 1, or n == 0), where X is constant # at `mean` and dividing by std_dev would raise ZeroDivisionError. if std_dev == 0.0: return 1.0 if mean > corrected_boundary else 0.0 # Phase 4: Standardize to a z-score (standard deviations from the mean) and evaluate P(Z > z). z_score = (corrected_boundary - mean) / std_dev return standard_normal_upper_tail(z_score)✅ Submit now — all tests should pass.
Intuition & how it works
Picture the exact Binomial distribution for 64 fair trials as a row of 65 wooden blocks centered at integers 0, 1, ..., 64, where each block j spans [j - 0.5, j + 0.5] and its area equals P(X = j). By the Central Limit Theorem (which states that the sum of many independent random trials closely follows a smooth bell-shaped Normal curve), we can drape a Normal curve with the same mean n * p and standard deviation sqrt(n * p * (1 - p)) over those blocks. Asking for P(X > k) means adding up blocks k + 1, k + 2, ..., which begins at the right edge of block k — namely k + 0.5. Shifting k to k + 0.5 before reading the smooth curve's area is called a continuity correction (adjusting an integer cutoff by half a unit so a continuous curve aligns with discrete unit-width histogram bars).
Summing exact Binomial probabilities term by term requires n - k separate combinatorial terms, and naive floating-point evaluation of comb(n, j) * p^j * (1 - p)^(n - j) overflows once n exceeds roughly 1,000. Conversely, plugging k into the Normal survival function without the + 0.5 continuity correction slices block k right down the middle, accidentally counting half of P(X = k) and inflating the error on n = 64, p = 0.5, k = 38 more than fortyfold (0.0668 vs exact 0.0517).
Let's trace Example 1 (n = 64, p = 0.5, k = 38):
- Mean mean = 64 * 0.5 = 32.0, standard deviation std_dev = sqrt(64 * 0.5 * 0.5) = 4.0.
- Continuity-corrected boundary for X > 38: 38 + 0.5 = 38.5.
- Standardize to a z-score (number of standard deviations from the mean): z = (38.5 - 32.0) / 4.0 = 1.625.
- Upper-tail area: P(Z > 1.625) = 0.5 * erfc(1.625 / sqrt(2)) ≈ 0.052081, within 0.00037 of the exact 0.051711.
Complexity
- Time:
O(1). Computingmean,std_dev,z_score, and onemath.erfcevaluation takes a fixed handful of floating-point operations regardless of how largenorkis (whereas summing the exact Binomial upper tail takesO(n - k)steps). - Space:
O(1). Only a few scalar float variables are stored in memory, with no arrays or recursion.
Edge cases
- Degenerate
p = 0.0,p = 1.0, orn = 0:std_devis0.0becauseXdeterministically equalsmean = n * p. Guardingif std_dev == 0.0:returns1.0ifmean > k + 0.5else0.0instead of raisingZeroDivisionError. k + 0.5equal tomean(e.g.,n = 9, p = 0.5, k = 4): Givesz_score = 0.0and0.5 * erfc(0.0) = 0.5by exact symmetry of the standard Normal curve.- Extreme upper tails (
z_scorelarge, e.g.,k = 200forn = 100): Evaluating0.5 * math.erfc(z / sqrt(2))avoids catastrophic cancellation (losing significant digits when subtracting two nearly equal floats like1.0 - 0.9999999999999999), returning a non-negative tiny tail value rather than premature0.0or-0.0. k < 0ork >= n: Although exactP(X > -1) = 1and exactP(X > n) = 0, an unbounded Normal curve still places tiny mass outside[0, n]; the function faithfully returns the Normal approximation requested by the contract.
Common mistakes
- Dividing by variance (
n * p * (1 - p)) instead of standard deviation (sqrt(n * p * (1 - p))): On Example 1 (6.5 / 16 = 0.40625instead of1.625), this wildly overestimates the tail as~0.342. - Shifting in the wrong direction (
k - 0.5instead ofk + 0.5): Using37.5includes bar38, computingP(X >= 38) ≈ 0.0846rather thanP(X > 38) ≈ 0.0521. - Omitting continuity correction (
kinstead ofk + 0.5): Using38.0givesz = 1.5and0.0668, a~29%relative error against the exact0.0517. - Returning
Phi(z)instead of1 - Phi(z): Standard Normal CDF calls return the lower tailP(Z <= z) ≈ 0.9479; forgetting to take the complement returns0.9479instead of0.0521. - Missing the
std_dev == 0.0check: CausesZeroDivisionErrorwheneverpis0,pis1, ornis0.
Alternative approaches
- Exact Binomial sum in log space (
O(n - k)orO(min(k, n - k))): Sumexp(lgamma(n + 1) - lgamma(j + 1) - lgamma(n - j + 1) + j * log(p) + (n - j) * log1p(-p))forj = k + 1 .. n, or call a statistical library's Binomial survival function (the built-in upper-tail routineP(X > k), such asscipy.stats.binom.sf(k, n, p)). Exact up to float precision, thoughO(n)instead ofO(1). - Poisson approximation (
O(k)): Whennis large andpis very small solambda = n * pis moderate, approximatingXby a Poisson distribution (a discrete count model for rare independent events with meanlambda) captures the right-skewed shape much better than a symmetric Normal curve. - Concentration bounds such as Hoeffding's inequality (
O(1)): Hoeffding's inequality (a non-asymptotic upper boundP(X - n*p >= t) <= exp(-2 * t^2 / n)valid for every finiten) gives a strict analytical ceiling (exp(-2 * 7^2 / 64) ≈ 0.216forX >= 39on Example 1), useful for worst-case guarantees though much looser than the Normal estimate.
Follow-up questions
- What happens to the quality of this Normal estimate when the trial probability is strongly skewed, say p = 0.02? Accuracy deteriorates sharply because
Binomial(100, 0.02)has mean2.0, standard deviation1.4, and heavy positive skewness (a measure of asymmetry; here(1 - 2p) / sqrt(n * p * (1 - p)) ≈ +0.69versus0atp = 0.5), meaning its right tail stretches out while counts are blocked below0. A symmetric bell curve underestimates that stretched upper tail — for instance,P(X > 5)is≈ 0.0062under the Normal approximation versus≈ 0.0155exact (off by 2.5x!) — while spilling≈ 0.037of impossible probability mass below-0.5. In this rare-event regime, either sum the exact Binomial terms or usePoisson(lambda = 2)(P(Y > 5) ≈ 0.0166). - Which rules of thumb on n and p govern whether a Normal tail estimate is trustworthy, and where do they break down? Practical guidelines require both
n * p >= 10andn * (1 - p) >= 10(occasionally>= 5near the median) so the mean sits several standard deviations clear of the hard boundaries0andn. Formally, the Berry–Esseen theorem (which bounds the largest absolute gap between a standardized sum's CDF andPhi(z)) shows the worst-case absolute CDF error decays at rateO((p^2 + (1 - p)^2) / sqrt(n * p * (1 - p))). However, far out in the tails (|z| > 3), a tiny absolute error still causes large relative error, so extreme-tail risk calculations should rely on exact Binomial sums, Poisson limits, or saddlepoint/Chernoff approximations. - Does the +0.5 continuity shift still matter once the trial count grows very large, such as n = 40,000? Its absolute effect shrinks at rate
1 / sqrt(n)because each discrete bar stays1unit wide whilestd_devgrows tosqrt(40000 * 0.25) = 100— so+0.5nudgeszby just0.5 / 100 = 0.005, changing central probabilities by at most~0.002. Even atn = 40,000, though, keeping+0.5noticeably sharpens tail relative accuracy: forP(X > 20200)(z ≈ 2), omitting the shift gives0.022750(1.2%relative error) whereas20200.5gives0.022482against the exact0.022481(< 0.005%error) at zero extra computational cost.
Follow-up questions
- What happens to the quality of this Normal estimate when the trial probability is strongly skewed, say p = 0.02?
- Which rules of thumb on n and p govern whether a Normal tail estimate is trustworthy, and where do they break down?
- Does the +0.5 continuity shift still matter once the trial count grows very large, such as n = 40,000?
Similar questions
- Exact and Poisson Tail Probabilities for Rare Trials
- 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
- Exact and Poisson Tail Probabilities for Rare Trials 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