numpy.round#

numpy.round(a, decimals=0, out=None)[源代码]#

均匀地四舍五入到给定的位数.

参数:
aarray_like

输入数据.

decimalsint, 可选

要舍入的小数位数(默认值:0).如果小数位数为负数,则指定小数点左侧的位置数.

outndarray, 可选

要在其中放置结果的替代输出数组.它必须具有与预期输出相同的形状,但如果需要,输出值的类型将被转换.有关更多详细信息,请参见 输出类型确定.

返回:
rounded_arrayndarray

a 类型相同的数组,包含四舍五入的值.除非指定了 out,否则会创建一个新数组.返回对结果的引用.

复数的实部和虚部分别四舍五入.四舍五入的结果是一个浮点数.

参见

ndarray.round

等效方法

around

这个函数的别名

ceil, fix, floor, rint, trunc

备注

对于恰好介于四舍五入的十进制值之间的值,NumPy 会四舍五入到最近的偶数值.因此 1.5 和 2.5 四舍五入到 2.0,-0.5 和 0.5 四舍五入到 0.0,等等.

np.round 使用了一个快速但有时不精确的算法来四舍五入浮点数数据类型.对于正的 decimals,它等价于 np.true_divide(np.rint(a * 10**decimals), 10**decimals),这由于IEEE浮点标准中十进制分数的不精确表示[R25ee6110317b-1]_ 和在按十的幂次缩放时引入的误差而产生误差.例如,注意下面多出的”1”:

>>> np.round(56294995342131.5, 3)
56294995342131.51

如果你的目标是打印具有固定小数位数的这些值,最好使用 numpy 的浮点打印例程来限制打印的小数位数:

>>> np.format_float_positional(56294995342131.5, precision=3)
'56294995342131.5'

浮点数打印例程使用一种精确但计算上要求更高的算法来计算小数点后的位数.

另外,Python 内置的 round 函数使用了一个更精确但更慢的 64 位浮点值算法:

>>> round(56294995342131.5, 3)
56294995342131.5
>>> np.round(16.055, 2), round(16.055, 2)  # equals 16.0549999999999997
(16.06, 16.05)

参考文献

[1]

“关于IEEE 754状态的讲义”, William Kahan, https://people.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF

示例

>>> import numpy as np
>>> np.round([0.37, 1.64])
array([0., 2.])
>>> np.round([0.37, 1.64], decimals=1)
array([0.4, 1.6])
>>> np.round([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([0., 2., 2., 4., 4.])
>>> np.round([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1,  2,  3, 11])
>>> np.round([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])