ste*_*fen 3 python floating-point rounding floating-accuracy
一半,即十进制的0.5,具有精确的二进制表示:0.1
然而,如果我将它四舍五入为整数,我得到0而不是1.我尝试使用Python和C,其行为相同.例如python代码:
>>> a,b,c = 0.49, 0.5, 0.51
>>> [round(x) for x in (a,b,c)]
[0, 0, 1]
>>> "%.0f %.0f %.0f" % (a,b,c)
'0 0 1'
Run Code Online (Sandbox Code Playgroud)
有趣的是,
>>> a,b,c = 0.049, 0.05, 0.051
>>> [round(x,1) for x in (a,b,c)]
[0.0, 0.1, 0.1]
>>> "%.1f %.1f %.1f" % (a,b,c)
'0.0 0.1 0.1'
Run Code Online (Sandbox Code Playgroud)
我知道许多类似的问题,例如Python舍入错误与浮点数,浮点算术的Python教程,以及每个计算机科学家应该知道的关于浮点运算的强制性.
如果数字具有精确的二进制表示,例如(十进制)0.5,是否应该正确舍入?
编辑:问题发生在3.4.3版本中,但不在2.7.6版本中
我知道他们改变了python 3中的round方法.
所以,在v2.7.3下:
In [85]: round(2.5)
Out[85]: 3.0
In [86]: round(3.5)
Out[86]: 4.0
Run Code Online (Sandbox Code Playgroud)
根据v3.2.3:
In [32]: round(2.5)
Out[32]: 2
In [33]: round(3.5)
Out[33]: 4
Run Code Online (Sandbox Code Playgroud)
我不知道它是否对你有所帮助,但由于我的声誉很低,因此我无法发表评论.
这里回答的问题更为恰当:Python 3.x舍入行为
| 归档时间: |
|
| 查看次数: |
654 次 |
| 最近记录: |