Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fa61d71

Browse files
authoredJul 13, 2020
Add files via upload
1 parent e292ddb commit fa61d71

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
 

‎maths/binomial_distribution.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""For more information about the Binomial Distribution -
2+
https://en.wikipedia.org/wiki/Binomial_distribution"""
3+
4+
5+
def binomial_distribution(k, n, p) -> float:
6+
"""
7+
8+
Returns probability of k successes out of n tries,
9+
with p probability for one success
10+
11+
use: binomial_distribution(k, n, p):
12+
k - successes
13+
n - independent Bernoulli trials
14+
p - probability for one succes
15+
16+
The function uses the factorial function
17+
in order to calculate the binomial coefficient
18+
19+
>>> binomial_distribution(3, 5, 0.7)
20+
0.30870000000000003
21+
22+
>>> binomial_distribution (2, 4, 0.5)
23+
0.375
24+
25+
>>> binomial_distribution (2, 4, -0.5)
26+
Traceback (most recent call last):
27+
...
28+
raise ValueError("p - Probability has to be in range of 1 - 0")
29+
ValueError: p - Probability has to be in range of 1 - 0
30+
"""
31+
if k > n:
32+
raise ValueError("""k must be lower or equal to n""")
33+
if n < 0 or k < 0 or type(k) != int or type(n) != int:
34+
raise ValueError("the function is defined for non-negative integers k and n")
35+
if p > 1 or p < 0:
36+
raise ValueError("p - Probability has to be in range of 1 - 0")
37+
probability = (p**k)*(1-p)**(n-k)
38+
# Calculate the binomial coefficient:
39+
# Calculate n! / k!(n-k)!
40+
coefficient = factorial(n)/(factorial(k)*factorial(n-k))
41+
42+
return probability * coefficient
43+
44+
45+
# Implementation of the factorial function,
46+
# used to calculate the binomial coefficient:
47+
def factorial(n) -> int:
48+
"""
49+
Factorial - The product of all positive integers less than or equal to n
50+
"""
51+
52+
if type(n) != int:
53+
raise ValueError("factorial(n) accepts only integer values")
54+
if n < 0:
55+
raise ValueError("factorial(n) works only for non-negative numbers")
56+
if n == 0:
57+
return 1
58+
result = 1
59+
for i in range(1, n+1):
60+
result *= i
61+
return result
62+
63+
if __name__ == "__main__":
64+
print ("Probability of 2 successes out of 4 trails")
65+
print ("with probability of 0.75 is : ")
66+
print (str(binomial_distribution(2, 4, 0.75)))

0 commit comments

Comments
 (0)
Please sign in to comment.