Python 2 中的 Python 3 舍入行为

标签 python

在 Python 2.x 中,内置的 round具有以下行为:

if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0)

在 Python 3.x 中,this has changed更常见的:

if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

有没有一种简单的方法可以在 Python 2.x 中实现这种行为?不幸的是,future_builtins模块不包括这个。也许我还没有找到另一个类似的模块?或者,另一种将 Python 3.x 函数拉入 Python 2.x 的方法?

显然,我可以编写一个产生所需行为的新函数,但我更好奇是否存在使用实际 Python 3.x 函数的解决方案,以避免增加不必要的复杂性和需要维护的代码。

最佳答案

除非你介意 numpy 依赖,numpy.around可以做的事情:

>>> from numpy import around
>>> around(0.5)
0
>>> around(-0.5)
-0
>>> around(1.5)
2.0

关于Python 2 中的 Python 3 舍入行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839140/

相关文章:

Python Mutagen 添加图像封面不起作用

python - 从多个模块记录到同一个日志文件

c# - 从 Python 运行 .NET COM 程序集。程序集 dll 的 Python 路径?

python - 为什么 Pandas 不会产生模糊的时间错误?

python - 如何在 C 中创建具有不同列的二维数组?

python - 为什么 numpy 不能计算长对象?

python - Pandas 基于多个匹配列值合并 2 个数据框

python - 从 Python 控制 "daemon-like"linux 脚本

python - Django:表单中未加载字段

python - tensorflow 更改检查点位置