【发布时间】:2016-06-29 12:45:41
【问题描述】:
一半,即十进制的 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'
有趣的是,
>>> 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'
我知道许多类似的问题,例如Python rounding error with float numbers、Python tutorial on floating point arithmetics 和强制性的What Every Computer Scientist Should Know About Floating-Point Arithmetic。
如果一个数字具有精确的二进制表示,例如(十进制)0.5,是否应该正确舍入?
编辑:该问题出现在 3.4.3 版中,但不在 2.7.6 版中
【问题讨论】:
-
我没有得到这些结果 - 我看到 0、1、1。您使用的是什么版本的 Python,在什么平台上?
-
请注意,虽然
0.5具有精确的二进制表示,但0.05没有 -
@HelloWorld 标记为重复
标签: python floating-point rounding floating-accuracy