【问题标题】:Why is rounding 0.5 (decimal) not exact? [duplicate]为什么舍入 0.5(十进制)不准确? [复制]
【发布时间】: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 numbersPython 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


【解决方案1】:

我知道他们在 python 3 中改变了 round 方法。

所以,在 v2.7.3 下:

In [85]: round(2.5)
Out[85]: 3.0

In [86]: round(3.5)
Out[86]: 4.0

v3.2.3 下:

In [32]: round(2.5)
Out[32]: 2

In [33]: round(3.5)
Out[33]: 4

我不知道它是否对您有帮助,但我将其发布为答案,因为由于我的声誉低,我无法发表评论。

这个问题在这里得到了更正确的回答:Python 3.x rounding behavior

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-12-31
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 2021-07-23
  • 1970-01-01
相关资源
最近更新 更多