Skip to content

Commit e2fe7b2

Browse files
committed
Fix binomial distribution overflow
1 parent 6e03a48 commit e2fe7b2

2 files changed

Lines changed: 10 additions & 5 deletions

File tree

‎maths/binomial_distribution.py‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
"""For more information about the Binomial Distribution -
22
https://en.wikipedia.org/wiki/Binomial_distribution"""
33

4-
from math import factorial
5-
4+
from math import comb
65

76
def binomial_distribution(successes: int, trials: int, prob: float) -> float:
87
"""
@@ -26,9 +25,7 @@ def binomial_distribution(successes: int, trials: int, prob: float) -> float:
2625
if not 0 < prob < 1:
2726
raise ValueError("prob has to be in range of 1 - 0")
2827
probability = (prob**successes) * ((1 - prob) ** (trials - successes))
29-
# Calculate the binomial coefficient: n! / k!(n-k)!
30-
coefficient = float(factorial(trials))
31-
coefficient /= factorial(successes) * factorial(trials - successes)
28+
coefficient = comb(trials, successes)
3229
return probability * coefficient
3330

3431

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
import pytest
3+
from maths.binomial_distribution import binomial_distribution
4+
5+
def test_large_number_of_trials() -> None:
6+
assert binomial_distribution(85, 171, 0.5) == pytest.approx(
7+
0.060749764626165485
8+
)

0 commit comments

Comments
 (0)