Skip to content

Commit df4a652

Browse files
Binomial Expansion (#12875)
* 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 * add URL
1 parent ea50993 commit df4a652

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

maths/binomial_expansion.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
See Also:
23+
https://en.wikipedia.org/wiki/Binomial_theorem
24+
25+
Examples:
26+
>>> binomial_expansion(2, 3, 2)
27+
25
28+
>>> binomial_expansion(100, -4, 3)
29+
884736
30+
>>> binomial_expansion(2, 2, -2)
31+
0.0625
32+
>>> binomial_expansion(0, 0, 3)
33+
0
34+
>>> binomial_expansion(-2, 2, -1)
35+
Traceback (most recent call last):
36+
...
37+
ZeroDivisionError: Cannot raise 0 to the negative power
38+
"""
39+
total = a + b
40+
if total == 0 and n < 0:
41+
raise ZeroDivisionError("Cannot raise 0 to the negative power")
42+
43+
abs_n = abs(n)
44+
value = sum(
45+
binomial_coefficient(abs_n, i) * (a ** (abs_n - i)) * (b**i)
46+
for i in range(abs_n + 1)
47+
)
48+
49+
return value if n >= 0 else 1 / value
50+
51+
52+
if __name__ == "__main__":
53+
import doctest
54+
55+
doctest.testmod()

0 commit comments

Comments
 (0)