Seeing some unexpected behavior with Python tonight. Why is the following printing out 'not equal'?!
num = 1.00
num -= .95
nickel = .05
if nickel != num:
print 'not equal'
else:
print 'equal'
Seeing some unexpected behavior with Python tonight. Why is the following printing out 'not equal'?!
num = 1.00
num -= .95
nickel = .05
if nickel != num:
print 'not equal'
else:
print 'equal'
What every computer scientist should know about floating point arithmetic.
>>> num = 1.00
>>> num
1.0
>>> num -= 0.95
>>> num
0.050000000000000044
>>> nickel = .05
>>> nickel
0.05
You might find the decimal module useful.
>>> TWOPLACES = Decimal(10) ** -2
>>> Decimal(1).quantize(TWOPLACES)-Decimal(0.95).quantize(TWOPLACES) == Decimal(0.05).quantize(TWOPLACES)
True
Or, alternatively:
import decimal
decimal.getcontext().prec = 2
decimal.Decimal(1.00) - decimal.Decimal(0.95)
I inferred from your naming of the nickel
variable that you were thinking about money. Obviously, floating point is the wrong Type for that.
This is a common floating point problem with computers. It has to do with how the computer stores floating point numbers. I would suggest giving What Every Computer Scientist Should Know About Floating-Point Arithmetic a quick read through.