MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / binomial_distribution

Function binomial_distribution

maths/binomial_distribution.py:7–32  ·  view source on GitHub ↗

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 >>> binomial_distribution(3, 5, 0.7) 0.30870000000000003 >>> binomial_distribution (2,

(successes: int, trials: int, prob: float)

Source from the content-addressed store, hash-verified

5
6
7def binomial_distribution(successes: int, trials: int, prob: float) -> float:
8 """
9 Return probability of k successes out of n tries, with p probability for one
10 success
11
12 The function uses the factorial function in order to calculate the binomial
13 coefficient
14
15 >>> binomial_distribution(3, 5, 0.7)
16 0.30870000000000003
17 >>> binomial_distribution (2, 4, 0.5)
18 0.375
19 """
20 if successes > trials:
21 raise ValueError("""successes must be lower or equal to trials""")
22 if trials < 0 or successes < 0:
23 raise ValueError("the function is defined for non-negative integers")
24 if not isinstance(successes, int) or not isinstance(trials, int):
25 raise ValueError("the function is defined for non-negative integers")
26 if not 0 < prob < 1:
27 raise ValueError("prob has to be in range of 1 - 0")
28 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)
32 return probability * coefficient
33
34
35if __name__ == "__main__":

Callers 1

Calls 1

factorialFunction · 0.90

Tested by

no test coverage detected