Exercise: Loops and functions

Time to put loops and functions together, the same way A Tour of Go does: by computing a square root with Newton's method.

Start with a guess z, say 1.0. Then improve it again and again:

z -= (z * z - x) / (2 * z)

Each step gets much closer. Stop when the change from one step to the next is tiny, say less than 1e-12.

Exercise: finish sqrt so it returns the square root of x for any x >= 0. Watch out for x == 0. The tests compare your answer with math.sqrt using close, because floats are rarely exactly equal.

Then print how many steps it took for a few values. It is fewer than you might guess.

Press Check to run the tests.