Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 421
yzahavi Avatar asked May 29 '26 18:05

yzahavi


1 Answers

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'
like image 79
lejlot Avatar answered Jun 01 '26 19:06

lejlot