In my python program, an if statement is not being entered. I have simplified the code to the following:
x = -5
while x < 5:
if (x == 0):
prin
Behold the power of the print statement...
Let us insert a print statement...
x = -5
while x < 5:
if (x == 0):
print 0
x += .01
print x
Running this program, and inspecting the output around 0 reveals the problem:
...
-0.13
-0.12
-0.11
-0.1
-0.0900000000001
-0.0800000000001
-0.0700000000001
-0.0600000000001
-0.0500000000001
-0.0400000000001
-0.0300000000001
-0.0200000000001
-0.0100000000001
-6.23077978101e-14
0.00999999999994
0.0199999999999
0.0299999999999
0.0399999999999
0.0499999999999
0.0599999999999
0.0699999999999
0.0799999999999
0.0899999999999
0.0999999999999
0.11
0.12
0.13
...
Oh boy, it is never actually equal to zero!
Solutions:
Use integers. Most reliable.
x = -500 # times this by a 100 to make it an integer-based program
while x < 500:
if (x == 0):
print 0
x += 1
Never test equality with floating point arithmetic, but rather use a range:
delta = 0.00001 #how close do you need to get
point = 0 #point we are interested in
if (point-delta) <= x <= (point+delta):
# do stuff