python - 使用 numpy.rint() 舍入到最接近的 int 与 0.5 不一致

标签 python numpy

numpy's round int似乎与它处理 xxx.5 的方式不一致

In [2]: np.rint(1.5)
Out[2]: 2.0

In [3]: np.rint(10.5)
Out[3]: 10.0

1.5 向上舍入,10.5 向下舍入。是否有一个原因?是不是the inaccuracy of floats的神器| ?

编辑

有没有办法获得所需的功能,其中 n.5 向上舍入,即 n = 偶数或奇数的 n+1?

最佳答案

因此,这种行为(如评论中所述)是一种非常传统的舍入形式,见 round half to even方法。也称为(根据大卫赫弗南)银行家的四舍五入。围绕此行为的 numpy 文档暗示他们正在使用这种类型的舍入,但也暗示 numpy 与 IEEE 浮点交互的方式可能存在问题格式。 (如下图)

Notes
-----
For values exactly halfway between rounded decimal values, Numpy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
to the inexact representation of decimal fractions in the IEEE
floating point standard [1]_ and errors introduced when scaling
by powers of ten.

是不是这样,老实说,我不知道。我知道 numpy 核心的大部分仍然是用 FORTRAN 77 编写的,它早于 IEEE 标准(1984 年制定),但我不知道 FORTRAN 77 是否有这里的界面有些问题。

如果您只想进行四舍五入,np.ceil 函数(通常是天花板函数)将执行此操作。如果您正在寻找相反的结果(总是向下取整),np.floor 函数将实现这一目标。

关于python - 使用 numpy.rint() 舍入到最接近的 int 与 0.5 不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28617841/

相关文章:

python - 从 。从模块导入 *

python - 如何找到二进制数中连续1的组数

python - numpy 奇特的广播用于特殊情况谜语

python - 如何使用笛卡尔坐标在 matplotlib 中绘制球体?

matlab - numpy reshape问题(matlab比较)

python - 在ubuntu上安装selenium webdriver时出错,使用python3,chrome

限制访问的 Python 属性

Python CApi 引用计数详细信息

python - 使用 toPandas 时强制将 null 一致转换为 nan

python - 使科学计数法从 numpy 数组中可读