numpy.round#

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

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

参数:
aarray_like

输入数据.

decimalsint, optional

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

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]

“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])