|
| 1 | +from maths.binomial_coefficient import binomial_coefficient |
| 2 | + |
| 3 | + |
| 4 | +def binomial_expansion(a: float, b: float, n: int) -> int | float: |
| 5 | + """ |
| 6 | + Compute the value of (a + b)^n using the Binomial Theorem. |
| 7 | +
|
| 8 | + This function works for both positive and negative integer exponents. |
| 9 | + It raises a ZeroDivisionError if the base (a + b) is 0 and n is negative. |
| 10 | +
|
| 11 | + Args: |
| 12 | + a: First term (int or float). |
| 13 | + b: Second term (int or float). |
| 14 | + n: Exponent (must be integer). |
| 15 | +
|
| 16 | + Returns: |
| 17 | + The result of the binomial expansion (a + b)^n. |
| 18 | +
|
| 19 | + Raises: |
| 20 | + ZeroDivisionError: If a + b == 0 and n < 0. |
| 21 | +
|
| 22 | + Examples: |
| 23 | + >>> binomial_expansion(2, 3, 2) |
| 24 | + 25 |
| 25 | + >>> binomial_expansion(100, -4, 3) |
| 26 | + 884736 |
| 27 | + >>> binomial_expansion(2, 2, -2) |
| 28 | + 0.0625 |
| 29 | + >>> binomial_expansion(0, 0, 3) |
| 30 | + 0 |
| 31 | + >>> binomial_expansion(-2, 2, -1) |
| 32 | + Traceback (most recent call last): |
| 33 | + ... |
| 34 | + ZeroDivisionError: Cannot raise 0 to the negative power |
| 35 | + """ |
| 36 | + total = a + b |
| 37 | + if total == 0 and n < 0: |
| 38 | + raise ZeroDivisionError("Cannot raise 0 to the negative power") |
| 39 | + |
| 40 | + abs_n = abs(n) |
| 41 | + value = sum( |
| 42 | + binomial_coefficient(abs_n, i) * (a ** (abs_n - i)) * (b**i) |
| 43 | + for i in range(abs_n + 1) |
| 44 | + ) |
| 45 | + |
| 46 | + return value if n >= 0 else 1 / value |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + import doctest |
| 51 | + |
| 52 | + doctest.testmod() |
0 commit comments