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
Others have pointed out the issue with floating-point numbers being unable to represent values exactly. If you need exact decimal representation of a number, you can use the Decimal
class:
from decimal import Decimal
x = Decimal(-5)
while x < 5:
if (x == 0):
print 0
x += Decimal(".01")
This will print 0
as you expect.
Note the use of a string for the increment. If you used Decimal(.01)
you'd have the same problem with accurate representation of 0.01, because you're converting from a floating-point number and have already lost the accuracy, so the class doesn't allow that.