Sub topic 13
Extending Powers to Negative Exponents
This chapter assumes you have read the previous chapter on exponentiation by squaring. It also assumes you know Python's // and % operators and that floats are approximate. Here we extend fast_power so that it accepts negative exponents without losing its O(log n) behavior.
The Mathematical Rule
For any nonzero x and positive integer n, a negative exponent means a reciprocal:
- x⁻ⁿ = 1 / xⁿ
- For example, 2⁻³ = 1 / 2³ = 1/8 = 0.125
The rule turns a problem we can't solve yet (a negative exponent) into one we already can (a positive exponent). This is the same move recursion always makes: reduce the input to a case that is already handled. In this function, the negative case does no repeated work of its own. It converts the problem once and then hands it to the existing algorithm.
The Implementation
from fractions import Fraction
def fast_power(x, n):
if n < 0:
if x == 0:
raise ZeroDivisionError("0 cannot be raised to a negative power")
return 1 / fast_power(x, -n)
if n == 0:
return 1
half = fast_power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
print(fast_power(2, 10)) # 1024
print(fast_power(2, -2)) # 0.25
print(fast_power(Fraction(2), -3)) # 1/8The negative branch runs at most once. After -n is passed in, every later call has a non-negative exponent. The total cost is still O(log |n|) multiplications plus one division.
Common Errors
Halving a Negative Exponent Directly
You might try to drop the negative branch and let the squaring logic handle negative n. That fails because Python's // rounds toward negative infinity:
print(-3 // 2) # -2
print(-1 // 2) # -1Once n reaches -1, the call n // 2 gives -1 again. The function then calls itself with the same arguments forever. It never reaches the base case n == 0 and eventually raises RecursionError. To avoid this, make the exponent non-negative before any halving happens.
Forgetting Zero
0⁻¹ would mean 1/0, which is undefined. Without the explicit check, Python still raises ZeroDivisionError from the 1 / ... line, but the explicit check gives a clearer message. Note that fast_power(0, 0) returns 1. That follows the usual programming convention and matches Python's 0 ** 0.
Surprise Float Results
The / operator always returns a float for integer inputs, so fast_power(2, -2) gives 0.25 and not an integer. Floats are approximate, so values like fast_power(3, -5) are rounded. If you need exact answers, pass a Fraction, as in the last example above. Then 1 / Fraction(8) stays exactly 1/8.
Reciprocal First or Last?
There are two ways to apply the rule:
| Approach | Code | Rounding behavior |
|---|---|---|
| Reciprocal last | `1 / fast_power(x, -n)` | Exact integer powering, then one rounded division |
| Reciprocal first | `fast_power(1 / x, -n)` | The rounded value `1/x` is multiplied repeatedly, so error can build up |
For integer x, taking the reciprocal last is usually more accurate, because every multiplication happens on exact integers. One caveat: for very large exponents the integer power gets huge, and dividing 1 by it can underflow to 0.0 or overflow when converted to a float. In that range you have to pick between exactness and speed.
Exercise
Trace fast_power(2, -3). List the calls made in order, and give the returned value.
Show answer
fastpower(2, -3) calls fastpower(2, 3), which calls fastpower(2, 1), which calls fastpower(2, 0) and gets 1. Then fastpower(2, 1) returns 112 = 2, and fastpower(2, 3) returns 222 = 8. Finally, fast_power(2, -3) returns 1 / 8 = 0.125.
Exercise
Suppose you delete the "if n < 0" branch and call fast_power(2, -1). What happens, and why?
Show answer
Since n = -1 is not 0, the function computes -1 // 2, which is -1 in Python, and calls fast_power(2, -1) again with the same arguments. It never reaches n == 0, so it recurses until Python raises RecursionError.