Python int float rounding

后端 未结 1 1395
滥情空心
滥情空心 2021-01-13 14:08

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 pro

相关标签:
1条回答
  • 2021-01-13 14:39

    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'
    
    0 讨论(0)
提交回复
热议问题