x = 25
epsilon = 0.01
step = 0.1
guess = 0.0
while guess <= x:
if abs(guess**2 -x) >= epsilon:
guess += step
if abs(guess**2 - x) >= epsilon:
print('failed')
else:
print('succeeded: ' + str(guess))
I am given this Python program which attempts to calculate the square root of a number x. For some reason, this program loops indefinitely and I'm not sure why.
There are only finitely many values of guess, because, after guess>x (i.e. when guess>=25.1,, the while loop then stops). The while command in the middle of the program is the only thing that loops, so what is happening?
guess = 5.0? Yourifstatement won't match butguess <= xstill true.