|
| 1 | +"""For more information about the Binomial Distribution - |
| 2 | + https://en.wikipedia.org/wiki/Binomial_distribution""" |
| 3 | +from math import factorial |
| 4 | + |
| 5 | + |
| 6 | +def binomial_distribution(successes: int, trials: int, prob: float) -> float: |
| 7 | + """ |
| 8 | + Return probability of k successes out of n tries, with p probability for one |
| 9 | + success |
| 10 | +
|
| 11 | + The function uses the factorial function in order to calculate the binomial |
| 12 | + coefficient |
| 13 | +
|
| 14 | + >>> binomial_distribution(3, 5, 0.7) |
| 15 | + 0.30870000000000003 |
| 16 | + >>> binomial_distribution (2, 4, 0.5) |
| 17 | + 0.375 |
| 18 | + """ |
| 19 | + if successes > trials: |
| 20 | + raise ValueError("""successes must be lower or equal to trials""") |
| 21 | + if trials < 0 or successes < 0: |
| 22 | + raise ValueError("the function is defined for non-negative integers") |
| 23 | + if not isinstance(successes, int) or not isinstance(trials, int): |
| 24 | + raise ValueError("the function is defined for non-negative integers") |
| 25 | + if not 0 < prob < 1: |
| 26 | + raise ValueError("prob has to be in range of 1 - 0") |
| 27 | + probability = (prob ** successes) * ((1 - prob) ** (trials - successes)) |
| 28 | + # Calculate the binomial coefficient: n! / k!(n-k)! |
| 29 | + coefficient = float(factorial(trials)) |
| 30 | + coefficient /= factorial(successes) * factorial(trials - successes) |
| 31 | + return probability * coefficient |
| 32 | + |
| 33 | + |
| 34 | +if __name__ == "__main__": |
| 35 | + from doctest import testmod |
| 36 | + |
| 37 | + testmod() |
| 38 | + print("Probability of 2 successes out of 4 trails") |
| 39 | + print("with probability of 0.75 is:", end=" ") |
| 40 | + print(binomial_distribution(2, 4, 0.75)) |
0 commit comments