Skip to content

Commit afbb826

Browse files
Merge pull request #4 from leonmkim/bug_binom_pmf
fix implementation of binom_pmf to handle large k/n
2 parents d35285c + 3f39042 commit afbb826

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

binomial_cis/binomial_helper.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,26 @@ def binom_pmf(k, n, p):
3131
Returns
3232
pmf: binomial pmf evaluated at k, n, p
3333
"""
34-
pmf = binom_coeff(n, k) * p**k * (1-p)**(n-k)
35-
36-
# safeguard against floating point errors
37-
pmf = min(1, max(0, pmf)) # unable to use np.clip()
34+
if p == 1:
35+
if k == n:
36+
pmf = 1
37+
else:
38+
pmf = 0
39+
elif p == 0:
40+
if k == 0:
41+
pmf = 1
42+
else:
43+
pmf = 0
44+
else:
45+
# Use the multiplicative formula for computational efficiency:
46+
# https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
47+
log_binom_coeff = 0
48+
for i in range(1, int(min(k, n - k)) + 1):
49+
log_binom_coeff += np.log(n - i + 1) - np.log(i)
50+
log_pmf = log_binom_coeff + k * np.log(p) + (n-k) * np.log1p(-p)
51+
pmf = np.exp(log_pmf)
52+
# safeguard against floating point errors
53+
pmf = min(1, max(0, pmf)) # unable to use np.clip()
3854
return pmf
3955

4056

0 commit comments

Comments
 (0)