user2916886
user2916886

Reputation: 845

Finding square root without using math.sqrt()?

I recently was working on finding the square root of a number in python without using sqrt(). I came across this code and am having difficulty in understanding the logic in this code:

def sqrt(x):
    last_guess= x/2.0
    while True:
        guess= (last_guess + x/last_guess)/2
        if abs(guess - last_guess) < .000001: # example threshold
            return guess
        last_guess= guess

More specifically the logic behind calculating guess in above code. Can anyone help me understanding the logic?

Upvotes: 0

Views: 2051

Answers (1)

heltonbiker
heltonbiker

Reputation: 27575

You can always use the power (**) operator with an inverse exponent:

a = 2 ** (1.0 / 2)
a
> 1.41421...

Upvotes: 2

Related Questions