Python int float rounding

While playing with python, I came across this:

a = 1/(2.2 - 2) print a #prints out 5.0 print int(a) #prints out 4 

I suspect the problem has something to do with the representation of binary numbers (the 1/5 expression in binary is equivalent to 1/3 in decimal). Can someone shed some light on this?

+4
source share
1 answer

You are absolutely right in your suspicions. The main reason is that 2.2 cannot be represented exactly as a float :

 In [38]: '%.20f' % 2.2 Out[38]: '2.20000000000000017764' 

The rest follows from this:

 In [45]: '%.20f' % (2.2 - 2) Out[45]: '0.20000000000000017764' In [46]: '%.20f' % (1 / (2.2 - 2)) Out[46]: '4.99999999999999555911' 
+4
source

All Articles