forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinomial_expansion.py
More file actions
55 lines (42 loc) · 1.43 KB
/
Copy pathbinomial_expansion.py
File metadata and controls
55 lines (42 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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.
See Also:
https://en.wikipedia.org/wiki/Binomial_theorem
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()