33/41
Part 7 of 7 · Follow-upsLearn and do

How do you find a real number to a tolerance?

The same loop finds a real number. Say you want x\sqrt{x}, the square root of x: it's the point where m2m^2, the middle squared, reaches x. With floats, mid = (lo + hi) / 2, and the moves become lo = mid or hi = mid.

The trap is the stopping rule. while hi - lo > 1e-12 found 2\sqrt{2} in 41 steps. For 1012\sqrt{10^{12}} it never stopped. After 10,000 steps, lo was 999999.9999999999 and hi was 1000000.0:

import math

lo, hi = 999999.9999999999, 1000000.0
print(math.nextafter(lo, hi) == hi)
print((lo + hi) / 2)
print(math.ulp(1e6))
True
1000000.0
1.1641532182693481e-10

math.nextafter(lo, hi) is the next float after lo, toward hi, and it is hi. So the two are neighbors, with no float between them, and the middle rounds to one of them. math.ulp(1e6) gives the gap between floats near a million: about 1.16e-10. No tolerance of 1e-12 can get under that gap.

Loop a fixed number of times instead. Each round halves the interval:

def square_root(x, rounds=100):
    lo, hi = 0.0, max(1.0, x)
    for _ in range(rounds):
        mid = (lo + hi) / 2
        if mid * mid < x:
            lo = mid
        else:
            hi = mid
    return hi

print(square_root(2), math.sqrt(2))
print(square_root(1e12), math.sqrt(1e12))
1.4142135623730951 1.4142135623730951
1000000.0 1000000.0

Return hi, the bound whose square is at least x. lo ends one float below it. Or stop on a tolerance relative to the size of the answer.

In the editor, write cube_root(x) with a fixed number of rounds, for any real x. Unlike a square root, a cube root exists for a negative number, so -8 must give -2. It prints the cube roots of 27, 1e18, 0.001 and -8.