Python浮点和int行为

Python浮点和int行为,python,floating-point-conversion,Python,Floating Point Conversion,当我试图检查浮点变量是否包含精确的整数值时,我得到了以下奇怪的行为。 我的代码: x = 1.7 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) print "----------------------" x = **2.7** print x, (x == int(x)) x +

当我试图检查浮点变量是否包含精确的整数值时,我得到了以下奇怪的行为。 我的代码:

x = 1.7  print x,  (x == int(x))   
x += 0.1  print x,  (x == int(x))
x += 0.1  print x,  (x == int(x))
x += 0.1  print x,  (x == int(x))
print "----------------------"

x = **2.7** print x,  (x == int(x))
x += 0.1  print x,  (x == int(x))
x += 0.1  print x,  (x == int(x))
x += 0.1  print x,  (x == int(x))
我得到以下奇怪的输出(最后一行是问题):


你知道为什么
2.0
true
3.0
false

问题不在于转换,而在于添加

int(3.0) == 3.0
返回True

正如所料

问题是浮点不是无限精确的,你不能期望2.7+0.1*3是3.0

>>> 2.7 + 0.1 + 0.1 + 0.1
3.0000000000000004
>>> 2.7 + 0.1 + 0.1 + 0.1 == 3.0
False
正如@SuperBiasedMan所建议的,值得注意的是,在OPs方法中,由于使用了打印(字符串转换),简化了数据表示以最大限度地提高可读性,因此问题在某种程度上被隐藏了起来

>>> print 2.7 + 0.1 + 0.1 + 0.1 
3.0
>>> str(2.7 + 0.1 + 0.1 + 0.1)
'3.0'
>>> repr(2.7 + 0.1 + 0.1 + 0.1)
'3.0000000000000004'

值得注意的是,由于
print
会为了可读性而忽略差异,因此没有清楚地显示差异,但是如果使用
repr(2.7+0.1+0.1+0.1)
则会显示真实值。如果更正更准确的值,它仍然会忽略一定数量的小数位,
>>> print 2.7 + 0.1 + 0.1 + 0.1 
3.0
>>> str(2.7 + 0.1 + 0.1 + 0.1)
'3.0'
>>> repr(2.7 + 0.1 + 0.1 + 0.1)
'3.0000000000000004'