Python int浮点舍入 [英] Python int float rounding

查看:69
本文介绍了Python int浮点舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在玩python时,我遇到了这个问题:

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



<我怀疑问题与二进制数字表示有关(以二进制形式表示1/5等于以十进制形式表示1/3)。有人可以帮忙澄清一下吗?

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?

推荐答案

您的怀疑是正确的。根本原因是2.2无法完全表示为 float

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'

其余部分如下:

In [45]: '%.20f' % (2.2 - 2)
Out[45]: '0.20000000000000017764'

In [46]: '%.20f' % (1 / (2.2 - 2))
Out[46]: '4.99999999999999555911'

这篇关于Python int浮点舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆