Reputation: 845
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
Reputation: 27575
You can always use the power (**
) operator with an inverse exponent:
a = 2 ** (1.0 / 2)
a
> 1.41421...
Upvotes: 2