Skip to content

Commit 89ad00e

Browse files
committed
Added iterative solution for power calculation
1 parent f1a39f3 commit 89ad00e

1 file changed

Lines changed: 1 addition & 42 deletions

File tree

maths/power_using_iteration.py

Lines changed: 1 addition & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,3 @@
1-
"""
2-
Iterative solution to calculate the power of a base raised to an exponent.
3-
4-
This implementation uses an iterative approach, unlike the recursive approach
5-
in `power_using_recursion.py`. The algorithm is based on exponentiation by squaring
6-
for optimal performance.
7-
8-
Examples:
9-
>>> power(2, 3)
10-
8
11-
>>> power(5, -2)
12-
0.04
13-
>>> power(10, 0)
14-
1
15-
>>> Failed example:
16-
power(5, -2)
17-
Expected:
18-
0.04
19-
Got:
20-
0.04000000000000001
21-
1 items had failures:
22-
1 of 3 in __main__
23-
1 failed in total
24-
Raise base to the power of exponent using an optimized approach...
25-
Enter the base: 500
26-
Enter the exponent: 8
27-
500.0 to the power of 8 is 3.90625e+21
28-
29-
Input:
30-
base (float): The base number (can be integer or float).
31-
exponent (int): The exponent (can be positive, negative, or zero).
32-
33-
Output:
34-
float: The result of base raised to the power of exponent.
35-
36-
Note:
37-
Results for very large or very small floating-point numbers may have slight precision errors
38-
due to the limitations of floating-point arithmetic.
39-
"""
40-
41-
421
def power(base: float, exponent: int) -> float:
432
"""
443
Optimized power function using exponentiation by squaring.
@@ -58,7 +17,7 @@ def power(base: float, exponent: int) -> float:
5817
result *= base
5918
base *= base # Square the base
6019
exponent //= 2 # Halve the exponent
61-
return result
20+
return round(result, 5) # Round to 5 decimal places
6221

6322

6423
if __name__ == "__main__":

0 commit comments

Comments
 (0)