Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions maths/binomial_distribution.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
"""For more information about the Binomial Distribution -
https://en.wikipedia.org/wiki/Binomial_distribution"""

from math import factorial
from math import comb, factorial

Check failure on line 4 in maths/binomial_distribution.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (F401)

maths/binomial_distribution.py:4:24: F401 `math.factorial` imported but unused help: Remove unused import: `math.factorial`


def binomial_distribution(successes: int, trials: int, prob: float) -> float:
"""
Return probability of k successes out of n tries, with p probability for one
success

The function uses the factorial function in order to calculate the binomial
coefficient
The function uses the comb function in order to calculate the binomial
coefficient safely without overflow.

>>> binomial_distribution(3, 5, 0.7)
0.30870000000000003
Expand All @@ -25,10 +25,12 @@
raise ValueError("the function is defined for non-negative integers")
if not 0 < prob < 1:
raise ValueError("prob has to be in range of 1 - 0")

Check failure on line 28 in maths/binomial_distribution.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (W293)

maths/binomial_distribution.py:28:1: W293 Blank line contains whitespace help: Remove whitespace from blank line
probability = (prob**successes) * ((1 - prob) ** (trials - successes))
# Calculate the binomial coefficient: n! / k!(n-k)!
coefficient = float(factorial(trials))
coefficient /= factorial(successes) * factorial(trials - successes)

Check failure on line 30 in maths/binomial_distribution.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (W293)

maths/binomial_distribution.py:30:1: W293 Blank line contains whitespace help: Remove whitespace from blank line
# Calculate the binomial coefficient safely using math.comb to avoid factorial overflow

Check failure on line 31 in maths/binomial_distribution.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (E501)

maths/binomial_distribution.py:31:89: E501 Line too long (91 > 88)
coefficient = float(comb(trials, successes))

Check failure on line 33 in maths/binomial_distribution.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (W293)

maths/binomial_distribution.py:33:1: W293 Blank line contains whitespace help: Remove whitespace from blank line
return probability * coefficient


Expand Down
Loading