0

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' 
mskfisher
  • 3,291
  • 4
  • 35
  • 48
Benjamin Powers
  • 3,186
  • 2
  • 18
  • 23

3 Answers3

6

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
voithos
  • 68,482
  • 12
  • 101
  • 116
2

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.

jgritty
  • 11,660
  • 3
  • 38
  • 60
  • I disagree, it's the same problem. `>>> Decimal(.05) == Decimal(1.00 - .95) >>> False` – jb. May 12 '12 at 03:35
  • 2
    `Decimal('1') - Decimal('.95') == Decimal('.05')` or `Decimal(str(1.00 - .95)) == Decimal('.05')` – jamylak May 12 '12 at 03:39
  • 2
    @jb. It's the same problem because you've converted the result of a floating point operation to a decimal. You need to have the operation done on decimals. You also have to be careful assigning decimals from floats. Note the difference between `Decimal(0.1)` and `Decimal('0.1')` – Paul S May 13 '12 at 23:53
0

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.

jb.
  • 9,921
  • 12
  • 54
  • 90