Jul 31, 2024

`round`

is fairly slow, and there’s no need for binary search or a test multiplication:

`def sqrt(x, precision=1E-10):`

last_guess = x

guess = x / 2

while abs(last_guess - guess) >= precision:

last_guess = guess

guess = ((x / guess) + guess) / 2

return guess

You take the average of `guess`

and `x / guess`

until you get the right answer, because you know that the right answer is somewhere between those two values.

It gives you the square root of 2 in 5 iterations, and of 2,000,000 in 15 iterations. (For math geeks, it’s basically Euler’s method, and you could do it faster with the Newton-Raphson method.)