From 48f850e8d9b309c78dd36ccfbf3c7932c8dce8f5 Mon Sep 17 00:00:00 2001 From: Pratham Dada Date: Thu, 12 Nov 2026 23:24:15 +0530 Subject: [PATCH] fix: prevent overflow in binomial_distribution for large trials using math.comb fix: prevent overflow in binomial_distribution for large trials using math.comb --- maths/binomial_distribution.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/maths/binomial_distribution.py b/maths/binomial_distribution.py index e29c8597a6e5..17bf9fa38990 100644 --- a/maths/binomial_distribution.py +++ b/maths/binomial_distribution.py @@ -1,7 +1,7 @@ """For more information about the Binomial Distribution - https://en.wikipedia.org/wiki/Binomial_distribution""" -from math import factorial +from math import comb, factorial def binomial_distribution(successes: int, trials: int, prob: float) -> float: @@ -9,8 +9,8 @@ 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 @@ -25,10 +25,12 @@ def binomial_distribution(successes: int, trials: int, prob: float) -> float: 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") + 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) + + # Calculate the binomial coefficient safely using math.comb to avoid factorial overflow + coefficient = float(comb(trials, successes)) + return probability * coefficient