python - 为什么舍入 0.5(十进制)不准确?

标签 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'

有趣的是,

>>> 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,它不应该被正确舍入吗?

edit: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

在 v3.2.3 下:

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

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

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

问题在这里得到更恰当的回答:Python 3.x rounding behavior

关于python - 为什么舍入 0.5(十进制)不准确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099977/

相关文章:

python - 如何使用 def 函数变量函数迭代 pandas df

python - 使用Python更新HTML文件中4个值的值

java - 十六进制 -> float 转换不准确

Java:通过扩展添加 float

rounding - Stata:舍入不正确?

javascript - 将数据从 Javascript 发送回 Python

python - Twitter 搜索 API : search by tweet id

c - 为什么我的输出结果是 0?与格式或公式有关吗?

java - 如何将数字四舍五入到一定范围内?

Fortran - 想要四舍五入到小数点后一位