Sub topic 13
Extending Powers to Negative Exponents
The fast_power function from the previous chapter works for any non-negative integer exponent. This chapter extends it to negative exponents. The math needs one line of code. Most of the chapter covers what can go wrong around that line: division by zero, infinite recursion caused by Python's floor division, and floating-point rounding.
This chapter assumes you already know:
- Exponentiation by squaring, as built in the previous chapter.
- Python's
//and%operators, and the fact that//rounds toward negative infinity. - The basic idea that Python floats are IEEE 754 doubles with limited precision.
The Identity Behind the Code
For a nonzero base x and a positive integer n, the definition is:
- x⁻ⁿ = 1 / xⁿ
The identity follows from the exponent rule xᵃ · xᵇ = xᵃ⁺ᵇ. For that rule to hold when a = n and b = −n, x⁻ⁿ must be whatever you multiply xⁿ by to get x⁰ = 1, and that is the reciprocal 1/xⁿ.
This gives the recursion a new case that reduces a negative exponent to a positive one. The existing code already handles positive exponents correctly. So the new case does not recurse on a smaller version of the same kind of problem. It moves the problem into a region where the old base case and recursive case already apply.
The Extended Function
Here is the function with the negative branch and a guard for a zero base:
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(-2, -3)) # -0.125
print(fast_power(5, 0)) # 1
print(fast_power(0, 0)) # 1The n < 0 check comes first, so it runs only once, on the outermost call. Every recursive call after that receives a non-negative exponent, which means the reciprocal is taken exactly once, at the top.
Cost
The negative branch adds one stack frame and one division. For |n| ≥ 1, the call count goes from ⌊log₂|n|⌋ + 2 to ⌊log₂|n|⌋ + 3, so the running time is still O(log |n|). For example, fast_power(2, -8) makes calls with exponents −8, 8, 4, 2, 1, 0, which is six calls.
Gotcha 1: Floor Division Causes Infinite Recursion
You might think the negative branch is unnecessary, because the halving step should eventually reach zero from either side. In Python it does not. The // operator rounds toward negative infinity, so halving a negative number never reaches zero:
| n | n // 2 | n % 2 |
|---|---|---|
| -5 | -3 | 1 |
| -3 | -2 | 1 |
| -2 | -1 | 0 |
| -1 | -1 | 1 |
The exponent −1 maps to itself. A version without the negative branch therefore recurses forever, until Python stops it:
def broken_power(x, n):
if n == 0:
return 1
half = broken_power(x, n // 2)
if n % 2 == 0:
return half * half
return half * half * x
try:
broken_power(2, -3)
except RecursionError as e:
print("RecursionError:", e)The base case n == 0 cannot be reached from any negative starting value. Use this as a general check for recursive functions: for every allowed input, the sequence of arguments must reach a base case. The induction argument from an earlier chapter depends on this. That argument proved the function correct for n ≥ 0 by induction on n. For negative n, correctness follows from the n ≥ 0 case plus the identity x⁻ⁿ = 1/xⁿ, and no induction over the negative integers is needed.
Gotcha 2: A Zero Base
0⁻ⁿ would equal 1/0ⁿ = 1/0, which is undefined. Without the guard, 1 / fast_power(0, 3) evaluates 1 / 0, and Python raises ZeroDivisionError anyway. The explicit guard is still worth keeping for two reasons:
- The error message names the real problem ("0 cannot be raised to a negative power") instead of a bare division by zero.
- The check happens before any recursion, so no work is wasted.
The built-in operator agrees: 0 ** -1 raises ZeroDivisionError. A zero float behaves differently. 0.0 ** -1 also raises ZeroDivisionError in Python, but in C, IEEE 754 pow(0.0, -1.0) returns infinity. If you port this code, check which behavior the target platform expects.
0 ** 0 is a separate case. The function returns 1, which matches Python's 0 ** 0 == 1 and the common convention in combinatorics and series. The negative-exponent guard does not affect it, because n < 0 is false there.
Gotcha 3: The Result Type Changes
For non-negative exponents, an integer base gives an exact integer result. For negative exponents, 1 / ... uses true division, so the result is a float:
| Call | Result | Type |
|---|---|---|
| `fast_power(2, 3)` | `8` | `int` |
| `fast_power(2, -3)` | `0.125` | `float` |
| `fast_power(3, -1)` | `0.333…` | `float` |
| `fast_power(2.0, 3)` | `8.0` | `float` |
This matches the built-in **, where 2 ** -3 is 0.125. If you need exact results, pass a Fraction. The arithmetic in fast_power is generic, and 1 / Fraction(...) returns a Fraction:
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(Fraction(2), -3)) # 1/8
print(fast_power(Fraction(3), -5)) # 1/243
print(fast_power(Fraction(2, 3), -2)) # 9/4The same function now works for int, float, and Fraction. It works because it only uses *, /, comparison with zero, and the literal 1. This is duck typing: any type that supports those operations with the usual meaning will work.
Design Choice: Invert First or Invert Last
You can place the reciprocal in two places:
- Invert last:
1 / fast_power(x, -n). Compute xⁿ, then take one reciprocal. - Invert first:
fast_power(1 / x, -n). Take the reciprocal of the base, then raise it to a positive power.
The two are equal mathematically, but they behave differently in floating point.
- With an integer base, invert-last computes xⁿ exactly as a Python
int. It then performs one true division. Python'sint / intis correctly rounded, so the final float is the closest double to the exact answer. - Invert-first converts
1 / xto an inexact float immediately. Each later multiplication rounds again, so the errors add up across O(log n) steps.
This script measures the difference against the exact value computed with Fraction:
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
invert_last_misses = 0
invert_first_misses = 0
for n in range(1, 200):
exact = float(Fraction(1, 3 ** n))
if fast_power(3, -n) != exact:
invert_last_misses += 1
if fast_power(1 / 3, n) != exact:
invert_first_misses += 1
print("invert last mismatches: ", invert_last_misses) # 0
print("invert first mismatches:", invert_first_misses)The invert-last count is always 0, because both sides are correctly rounded versions of the same exact value. The invert-first count is usually greater than zero. Use invert-last.
Range: Overflow and Underflow
Invert-last has an edge case with float bases. fast_power(2.0, 1100) overflows to inf, because float multiplication in Python returns inf on overflow and does not raise an error. Then 1 / inf is 0.0. The exact answer 2⁻¹¹⁰⁰ is below the smallest positive double (about 4.9 × 10⁻³²⁴), so 0.0 is the correctly rounded result here as well. For float bases close to 1, such as 1.0001, the intermediate result can overflow while the true reciprocal is still representable. In that narrow range, invert-first can be more accurate. If your inputs live there, use math.pow or the built-in **, which are implemented with more care for these ranges.
Testing Against the Built-in
A short property test compares the function with Python's ** over many signs and bases:
import math
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
for x in [2, 3, -2, -3, 0.5, 1.5, 10]:
for n in range(-20, 21):
got = fast_power(x, n)
want = x ** n
assert math.isclose(got, want, rel_tol=1e-12), (x, n, got, want)
for n in range(-5, 0):
try:
fast_power(0, n)
raise AssertionError("expected ZeroDivisionError")
except ZeroDivisionError:
pass
print("all tests passed")The test uses math.isclose rather than == because float bases with positive exponents can round differently from the built-in. Negative bases work without special handling: the sign of half * half * x comes out correctly for odd exponents, and the reciprocal keeps that sign.
Exercise
List every (x, n) argument pair that fast_power(2, -6) is called with, in order, and give the return value.
Show answer
The calls are (2, -6), (2, 6), (2, 3), (2, 1), (2, 0). fast_power(2, 6) returns 64, so the result is 1 / 64 = 0.015625, a float.
Exercise
Without the n < 0 branch, why does fast_power(2, -3) never reach the base case, and which exponent does it get stuck on?
Show answer
Python's // rounds toward negative infinity, so the exponents go -3, -2, -1, and then -1 // 2 is -1 again. The value -1 maps to itself, n never becomes 0, and the recursion continues until Python raises RecursionError.
Exercise
fast_power(4, -1) returns 0.25, but you need the exact rational value. What is the smallest change to the call, not the function, that gives it?
Show answer
Pass a Fraction as the base: fast_power(Fraction(4), -1) returns Fraction(1, 4), because 1 / Fraction(4) stays a Fraction.
Exercise
For an integer base x and negative n, explain why 1 / fastpower(x, -n) produces the correctly rounded float, while fastpower(1 / x, -n) may not.
Show answer
With an integer base, fast_power(x, -n) is an exact Python int, and int / int true division is correctly rounded, so there is only one rounding step. Inverting first makes 1 / x inexact right away, and each of the O(log n) multiplications that follow rounds again, so the errors can add up.