为什么舍入0.5(十进制)不精确? [英] Why is rounding 0.5 (decimal) not exact?

查看:124
本文介绍了为什么舍入0.5(十进制)不精确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一半,即十进制的0.5,具有精确的二进制表示形式:0.1

One half, i.e. 0.5 in decimal, has an exact binary representation: 0.1

尽管如此,如果我将其四舍五入为整数,我得到的是0而不是1.我在Python和C中尝试过,它们的行为相同.例如. python代码:

Nevertheless, if I round it to integer, I get 0 instead of 1. I tried in Python and C, which behave the same. E.g. the python code:

>>> 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舍入错误

I am aware of Numerous similar questions, e.g. Python rounding error with float numbers, the Python tutorial on floating point arithmetics, and the obligatory What Every Computer Scientist Should Know About Floating-Point Arithmetic.

如果数字具有精确的二进制表示形式(例如(十进制)0.5),是否应该正确舍入?

If a number has an exact binary representation, such as (decimal) 0.5, shouldn't it be rounded correctly?

此问题在版本3.4.3中发生,但在版本2.7.6中没有发生

edit: The issue occurs in version 3.4.3, but not in version 2.7.6

推荐答案

我知道他们更改了python 3中的round方法.

I know they changed the round method in python 3.

因此,在v2.7.3下:

So, under 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

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

I don't know if it helps you but I am posting it as answer since I can't comment due to my low reputation.

在这里可以更正确地回答问题: Python 3.x舍入行为

The question is answered more properly here : Python 3.x rounding behavior

这篇关于为什么舍入0.5(十进制)不精确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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