From b1837e1c3bf0159da9e18b1304c7db1d676776a0 Mon Sep 17 00:00:00 2001 From: Daniel Heras Quesada Date: Tue, 18 Nov 2025 01:52:08 +0100 Subject: [PATCH] feat: binomial distribution --- src/main.py | 8 +++++++- src/modules/probability.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 7c9e113..af288eb 100644 --- a/src/main.py +++ b/src/main.py @@ -3,11 +3,17 @@ from sympy import diff, limit, oo, symbols from modules.math import ( test_math_module ) +from modules.probability import ( + test_probability_module +) from modules.strings import t_strings if __name__=="__main__": t_strings() print(">> Math module") - test_math_module() + # test_math_module() + print(">>>>>>>>>>>>>>>>>>>>") + print(">> Probability module") + test_probability_module() print(">>>>>>>>>>>>>>>>>>>>") diff --git a/src/modules/probability.py b/src/modules/probability.py index 43f72ab..d3e2ea9 100644 --- a/src/modules/probability.py +++ b/src/modules/probability.py @@ -2,9 +2,41 @@ ## "Essential Math for Data Science" - Thomas Nield ## Chaper 2 - Probability +from scipy.stats import binom +from math import factorial + # 2.0 odds means than an events has twice the probabilities to happen than not def p_odds_to_probability(o): return (o / (1 + o)) def p_probability_to_odds(p): return (p / (1 - p)) + +## Binomial distribution +def p_binomial_distribution_example(): + n = 10 + p = 0.9 + + for k in range(n + 1): + probability = binom.pmf(k, n, p) + print("{0} >> {1}".format(k, probability)) + +def binomial_coeficient(pool, count): + return factorial(pool) / (factorial(count) * factorial(pool - count)) + +def p_binomial_distribution_scratch(p, n): + # For each number calc the probability of that exact number of outcomes (no order) + for k in range(n + 1): + # 1. Simple combinatory with the binomial coeficient (combinations of k elements out of a pool of n without repetition without order) + combinatory = binomial_coeficient(n, k) + # 2. Probability of success, the probability of making it k times + probability_of_success = p ** k # p * p, k times + # 3. Probability of failure, inverse of the success + probability_of_failure = (1 - p) ** (n - k) # inverse of probability the rest of the times + k_binomital_distribution_probability = combinatory * probability_of_success * probability_of_failure + print("[{0}]: {1}".format(k, k_binomital_distribution_probability)) + + +def test_probability_module(): + p_binomial_distribution_example() + p_binomial_distribution_scratch(0.9, 10)