简体   繁体   中英

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 ?

the problem is not with conversion but with addition .

int(3.0) == 3.0

returns 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 + 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

>>> 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM