File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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-
421def 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
6423if __name__ == "__main__" :
You can’t perform that action at this time.
0 commit comments