Calculate Upper-Tail Probability for Binomial Distribution
Arrays & HashingAuto-graded · 22 test casesLast updated
Compute the exact cumulative probability P(X ≥ k) for a binomial random variable, testing understanding of numerical stability in probability calculations.
You need to compute the upper-tail probability for a binomial distribution. Given a number of independent trials n, a threshold k, and a success probability p for each trial, calculate the exact probability that a binomial random variable X ~ Binomial(n, p) takes on a value of at least k.
Mathematically, compute:
P(X ≥ k) = Σ (from i=k to n) C(n,i) * p^i * (1-p)^(n-i)
where C(n,i) denotes the binomial coefficient "n choose i".
Your implementation must handle edge cases correctly and maintain numerical stability even when intermediate values would overflow or underflow in naive implementations.
Edge case rules:
- If
k ≤ 0, return1.0(the probability that X is at least 0 is certain) - If
k > n, return0.0(impossible to get more successes than trials) - If
p ≤ 0.0, return0.0(no successes possible) - If
p ≥ 1.0, return1.0(all trials succeed, so X = n ≥ k for any valid k)
Constraints:
0 ≤ n ≤ 10,0000 ≤ k ≤ n + 10.0 ≤ p ≤ 1.0- Your solution must be numerically stable (use logarithms to avoid overflow/underflow)
- Return a float representing the probability
Examples
Example 1
Input: binomial_upper_tail(3, 2, 0.2)
Output: 0.1040000000000001
Example 2
Input: binomial_upper_tail(100, 40, 0.2)
Output: 0.000003608420114640808
Hints
Hint 1
Work in log-space to prevent numerical overflow when computing large factorials and powers
Hint 2
Use the log-sum-exp trick: factor out the maximum log-probability before exponentiating and summing
Hint 3
The lgamma function computes log(Γ(x)) = log((x-1)!) stably, and log1p(x) computes log(1+x) accurately for small x
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The straightforward approach of computing binomial probabilities directly fails due to numerical overflow. Factorials and powers grow extremely rapidly—for instance, 100! exceeds the range of standard floating-point numbers. Instead, we work entirely in log-space and apply the log-sum-exp trick.
Step 1: Handle edge cases
Before any computation, check boundary conditions where the answer is immediate: k ≤ 0 (certain event), k > n (impossible event), or degenerate probability values.
Step 2: Compute log-probabilities
For each value x from k to n, the probability mass is:
P(X = x) = C(n,x) * p^x * (1-p)^(n-x)
Taking logarithms:
log P(X = x) = log(n!) - log(x!) - log((n-x)!) + x*log(p) + (n-x)*log(1-p)
We use math.lgamma(m+1) to compute log(m!) stably, and math.log1p(-p) to compute log(1-p) accurately even when p is close to 1.
Step 3: Apply log-sum-exp trick
We need to compute Σ exp(log_i) where log_i are the log-probabilities. Direct exponentiation can underflow. The trick is:
Σ exp(log_i) = exp(M) * Σ exp(log_i - M)
where M = max(log_i). This ensures the largest term becomes exp(0) = 1, preventing underflow while all terms remain ≤ 1.
Step 4: Sum carefully
Use math.fsum for accurate floating-point summation, which reduces accumulated rounding errors.
Correctness
The binomial probability formula is exact by definition. Working in log-space preserves the mathematical identity while avoiding floating-point overflow and underflow. The log-sum-exp technique is a standard numerical recipe that maintains precision across the full range of representable values.
Complexity
- Time: O(n - k + 1), since we compute one log-probability per value from k to n
- Space: O(n - k + 1) to store the log-probability array
For the worst case where k = 0, this is O(n) time and space. When k is close to n, both are small.
Implementation
import math
def binomial_upper_tail(n: int, k: int, p: float) -> float:
if k <= 0:
return 1.0
if k > n:
return 0.0
if p <= 0.0:
return 0.0
if p >= 1.0:
return 1.0
log_p = math.log(p)
log_q = math.log1p(-p)
logs = []
for x in range(k, n + 1):
log_prob = (
math.lgamma(n + 1)
- math.lgamma(x + 1)
- math.lgamma(n - x + 1)
+ x * log_p
+ (n - x) * log_q
)
logs.append(log_prob)
max_log = max(logs)
return math.exp(max_log) * math.fsum(math.exp(value - max_log) for value in logs)