[英]Python float and int behavior
when i try to check whether float variable contain exact integer value i get the folowing strange behaviour. 当我尝试检查浮点变量是否包含完全整数值时,我得到了下面的奇怪行为。 My code :
我的代码:
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))
I get the folowing strange output (last line is the problem): 我得到了下面的奇怪输出(最后一行是问题):
1.7 False
1.8 False
1.9 False
2.0 True
----------------------
2.7 False
2.8 False
2.9 False
3.0 False
Any idea why 2.0
is true
and 3.0
is false
? 知道为什么
2.0
是true
而3.0
是false
吗?
the problem is not with conversion but with addition . 问题不在于转换,而在于添加 。
int(3.0) == 3.0
returns True 返回True
as expected. 正如所料。
The probelm is that floating points are not infinitely accurate, and you cannot expect 2.7 + 0.1 * 3 to be 3.0 问题是浮点不是无限精确的,你不能指望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
As suggested by @SuperBiasedMan it is worth noting that in OPs approach the problem was somehow hidden due to the use of printing (string conversion) which simplifies data representation to maximize readability 正如@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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.