numpy.round#

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

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

参数:
aarray_like

输入数据.

decimals整数,可选

要四舍五入到的小数位数(默认值: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 * 10decimals), 10decimals) ,由于 IEEE 浮点标准 [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]

“Lecture Notes on the Status of 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])