本文介绍了Python3舍入到最接近的偶数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python3.4会四舍五入到最接近的偶数(在平局的情况下).

Python3.4 rounds to the nearest even (in the tie-breaker case).

>>> round(1.5)
2
>>> round(2.5)
2

但是似乎只有四舍五入为整数时才这样做.

But it only seems to do this when rounding to an integer.

>>> round(2.75, 1)
2.8
>>> round(2.85, 1)
2.9

在上面的最后一个示例中,当四舍五入到最接近的偶数时,我希望答案是2.8.

In the final example above, I would have expected 2.8 as the answer when rounding to the nearest even.

为什么两种行为之间存在差异?

Why is there a discrepancy between the two behaviors?

推荐答案

浮点数仅是近似值; 2.85不能精确地表示为 :

Floating point numbers are only approximations; 2.85 cannot be represented exactly:

>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'

它略高于 2.85.

0.5和0.75 可以用二进制分数精确表示(分别为1/2和1/2 + 1/4).

0.5 and 0.75 can be represented exactly with binary fractions (1/2 and 1/2 + 1/4, respectively).

round()函数​​对此进行了明确记录:

这篇关于Python3舍入到最接近的偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:53