Python square root algorithm

I’m learning Sedgewick’s Algorithms and the examples are all in Java. So I’m converting them to Python for my own understanding.
Here’s the first example I came across in the first chapter, for finding a square root:
def sqrt(i):
    if i<=0:
        return None
    x = i
    e=1e-15
    while (x-i/x) > (e):
        x=(i/x+x)/2.0
    return x
In [30]: sqrt(4)
Out[30]: 2.0
In [31]: sqrt(9)
Out[31]: 3.0
In [32]: sqrt(142857)
Out[32]: 377.96428402694346
I ought to raise an Exception instead of returning None in the beginning. My maths skills have turned painfully rusty — it took me a good 5-10 minutes of reading the example in the book before I understood that it worked, after which I wrote this version without too much trouble.

Hopefully I’ll stick with this project through to the end.

Leave a Reply