From 16efeef8e1f7c5fa5ec44ef0495463a45caf6db2 Mon Sep 17 00:00:00 2001 From: Isaac Shoebottom Date: Sat, 17 Feb 2024 22:09:00 -0400 Subject: [PATCH] Add functions not supported by micropython --- distribution.py | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/distribution.py b/distribution.py index 04cc0fa..a40ae08 100644 --- a/distribution.py +++ b/distribution.py @@ -1,6 +1,29 @@ import math +def factorial(n): + """ + Computes the factorial of a number. + :param n: The number to compute the factorial of. + :return: Returns the factorial of the number. + """ + if n == 0: + return 1 + for i in range(1, n): + n *= i + return n + + +def combination(n, r): + """ + Computes the combination of n choose r. + :param n: The number of items. + :param r: The number of items to choose. + :return: Returns the number of ways to choose r items from n items. + """ + return factorial(n) / (factorial(r) * factorial(n - r)) + + def bnd(x, n, p): """ Computes the binomial distribution. @@ -9,7 +32,7 @@ def bnd(x, n, p): :param p: Probability of success. :return: Returns the probability of getting x successes in n trials. """ - return math.comb(n, x) * p ** x * (1 - p) ** (n - x) + return combination(n, x) * p ** x * (1 - p) ** (n - x) def bnd_mean(n, p): @@ -187,7 +210,7 @@ def hgd(x, N, n, k): :param k: Number of successes in the population. :return: Returns the probability of getting x successes in n draws from a population of size N with k successes. """ - return (math.comb(k, x) * math.comb(N - k, n - x)) / math.comb(N, n) + return (combination(k, x) * combination(N - k, n - x)) / combination(N, n) def hgd_mean(N, n, k): @@ -278,7 +301,7 @@ def pd(x, l): :param l: Average number of occurrences. :return: Returns the probability of getting x occurrences. """ - return (l ** x * math.e ** -l) / math.factorial(x) + return (l ** x * math.e ** -l) / factorial(x) def pd_mean(l):