看到今晚Python的一些意外行为。为什么以下打印出“不等于”?Python浮点等于奇怪
num = 1.00
num -= .95
nickel = .05
if nickel != num:
print 'not equal'
else:
print 'equal'
看到今晚Python的一些意外行为。为什么以下打印出“不等于”?Python浮点等于奇怪
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
您可能会发现decimal模块有用。
>>> TWOPLACES = Decimal(10) ** -2
>>> Decimal(1).quantize(TWOPLACES)-Decimal(0.95).quantize(TWOPLACES) == Decimal(0.05).quantize(TWOPLACES)
True
,或者:
import decimal
decimal.getcontext().prec = 2
decimal.Decimal(1.00) - decimal.Decimal(0.95)
我从你的nickel
变量,你是想赚钱的命名推断。显然,浮点数是错误的类型。
这是计算机常见的浮点问题。它与计算机如何存储浮点数有关。我建议快速阅读What Every Computer Scientist Should Know About Floating-Point Arithmetic。
http://docs.python.org/tutorial/floatingpoint.html – jamylak
好东西伙计。已经有一段时间了,从未遇到它。谢谢。 –