I am doing this in python with while loop. It's not terminating.
x = 2.0
ans = 0
while ans**2 != abs(x):
print (ans)
ans = ans + 0.001
if ans**2 == abs(x):
print(ans)
I am doing this in python with while loop. It's not terminating.
x = 2.0
ans = 0
while ans**2 != abs(x):
print (ans)
ans = ans + 0.001
if ans**2 == abs(x):
print(ans)
Even this doesn't work like you'd want it to:
>>> (2 ** 0.5) ** 2 == 2
False
For some numbers it does, though, even for non-squares:
>>> (11 ** 0.5) ** 2 == 11
True
It can even go wrong with simpler calculations:
>>> 0.1 + 0.2 == 0.3
False
The problem is that in general, the computer doesn't represent floating point numbers exactly. You only get a number close to the correct number. So you shouldn't do an exactness-test but a closeness-test (check whether the difference is less than some small number small enough to satisfy your needs).
>>> abs((2 ** 0.5) ** 2 - 2) < 1e-10
True
You shouldn't use !=
or ==
operators to compare floating point variables, as it's improbably you'll ever hit the exact square root with such a naive algorithm. Instead, you should define the acceptable error you're willing to tolerate and continue until you've hit a number with a smaller error than that. However, then may not be sufficient. Since you have a constant increment, you may very well find that you'll never get close enough to the square root you're searching for, and therefore, need an additional safeguard to not pass the required result and continue to infinity:
x = 2.0
ans = 0
step = 0.001
delta = 0.0001
while ans**2 < x and abs (ans**2 - x) > delta:
ans = ans + step
# Done looping, found the best ans for ans**2<x.
# Check one additional value where ans**2>x
# and choose the one with the smaller delta
overAns = ans + step
if abs (overAns ** 2 - x) < abs (ans ** 2 - x):
print overAns
else:
print ans