Python float equality weirdness

2019-01-29 07:11发布

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' 

3条回答
来,给爷笑一个
2楼-- · 2019-01-29 07:31

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
查看更多
劫难
3楼-- · 2019-01-29 07:47

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.

查看更多
倾城 Initia
4楼-- · 2019-01-29 07:51

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.

查看更多
登录 后发表回答