Python舍入不一致 [英] Python Rounding Inconsistently

查看:70
本文介绍了Python舍入不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我告诉 Python v. 3.4.3,round(2.5),那么它输出 2.如果我告诉它 round(1.5) 那么它也会输出 2.类似地,round(3.5) 给出 4,而 round(4.5) 也给出 4.不过,我需要 Python 来保持一致性.具体来说,它需要在我输入两个整数中间的数字时四舍五入.所以 round(1.5) = 1round(2.5) = 2,而 round(1.6) = 2 和往常一样.

If I tell Python v. 3.4.3, round(2.5), then it outputs 2. If I tell it round(1.5) then it outputs 2 as well, though. Similarly, round(3.5) gives 4, while round(4.5) gives 4 as well. I need Python to round with consistency, though. Specifically, it needs to round anytime I input a number halfway between two integers. So round(1.5) = 1 and round(2.5) = 2, while round(1.6) = 2 and such, as usual.

我该如何解决这个问题?

How can I resolve this?

我已经阅读了 round 函数的文档并理解这是它的预期行为.我的问题是,我怎样才能改变这种行为,因为为了我的目的,我需要 1.5 舍入.

I've already read the documentation for the round function and understand that this is its intended behavior. My question is, how can I alter this behavior, because for my purposes I need 1.5 round down.

推荐答案

与 Python 2 相比,Python 3 使用不同的舍入行为:它现在使用所谓的银行家舍入"(维基百科):当整数部分为奇数时,数字从零开始四舍五入;当整数部分为偶数时,是否向零四舍五入.

Python 3 uses a different rounding behaviour compared to Python 2: it now uses so-called "banker's rounding" (Wikipedia): when the integer part is odd, the number is rounded away from zero; when the integer part is even, is it rounded towards zero.

这样做的原因是为了避免偏差,因为 0.5 处的所有值都从零舍入(然后例如求和).

The reason for this is to avoid a bias, when all values at .5 are rounded away from zero (and then e.g. summed).

这是您看到的行为,实际上是一致的.这可能与您习惯的不同.

This is the behaviour you are seeing, and it is in fact consistent. It's perhaps just different than what you are used to.

这篇关于Python舍入不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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