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 binary number representation (expressing 1/5 in binary is tantamount to expressing 1/3 in decimal). Can someone please shed some light on this?
You are quite right in your suspicion. The root cause 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'
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.