From 89b05ad2a3a2d41c244ba9341af5f75bd787b510 Mon Sep 17 00:00:00 2001 From: aditya7balotra Date: Sat, 2 Aug 2025 04:24:08 +0530 Subject: [PATCH 1/2] Add binomial_expansion function building on binomial_coefficient - Computes (a + b)^n for both positive and negative integer exponents - Uses existing binomial_coefficient function for term computation - Raises ZeroDivisionError when base is 0 and exponent is negative - Includes doctests and example cases --- maths/binomial_expansion.py | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 maths/binomial_expansion.py diff --git a/maths/binomial_expansion.py b/maths/binomial_expansion.py new file mode 100644 index 000000000000..aeae0cf1da72 --- /dev/null +++ b/maths/binomial_expansion.py @@ -0,0 +1,52 @@ +from maths.binomial_coefficient import binomial_coefficient + + +def binomial_expansion(a: float, b: float, n: int) -> int | float: + """ + Compute the value of (a + b)^n using the Binomial Theorem. + + This function works for both positive and negative integer exponents. + It raises a ZeroDivisionError if the base (a + b) is 0 and n is negative. + + Args: + a: First term (int or float). + b: Second term (int or float). + n: Exponent (must be integer). + + Returns: + The result of the binomial expansion (a + b)^n. + + Raises: + ZeroDivisionError: If a + b == 0 and n < 0. + + Examples: + >>> binomial_expansion(2, 3, 2) + 25 + >>> binomial_expansion(100, -4, 3) + 884736 + >>> binomial_expansion(2, 2, -2) + 0.0625 + >>> binomial_expansion(0, 0, 3) + 0 + >>> binomial_expansion(-2, 2, -1) + Traceback (most recent call last): + ... + ZeroDivisionError: Cannot raise 0 to the negative power + """ + total = a + b + if total == 0 and n < 0: + raise ZeroDivisionError("Cannot raise 0 to the negative power") + + abs_n = abs(n) + value = sum( + binomial_coefficient(abs_n, i) * (a ** (abs_n - i)) * (b**i) + for i in range(abs_n + 1) + ) + + return value if n >= 0 else 1 / value + + +if __name__ == "__main__": + import doctest + + doctest.testmod() From 41b07e2e215799b6870b7dd342137e1e1cbe15f9 Mon Sep 17 00:00:00 2001 From: aditya7balotra Date: Sat, 2 Aug 2025 05:12:15 +0530 Subject: [PATCH 2/2] add URL --- maths/binomial_expansion.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/maths/binomial_expansion.py b/maths/binomial_expansion.py index aeae0cf1da72..d09e7c74f9a1 100644 --- a/maths/binomial_expansion.py +++ b/maths/binomial_expansion.py @@ -19,6 +19,9 @@ def binomial_expansion(a: float, b: float, n: int) -> int | float: Raises: ZeroDivisionError: If a + b == 0 and n < 0. + See Also: + https://en.wikipedia.org/wiki/Binomial_theorem + Examples: >>> binomial_expansion(2, 3, 2) 25