为舍入设置明确的限制

Setting explicit limits for rounding

是否有更优雅的方式来设置明确的舍入限制?

我用的是:

arr= #original array
rnd_lim=1.7
rounded_arr=np.where(arr.__ge__(rnd_lim), arr,np.floor( arr))
rounded_arr=np.where(rounded_arr.__lt__(rnd_lim), rounded_arr,np.ceil(rounded_arr))

输入:

array([1.115, 1.722, 1.21 , 2.   , 1.025, 2.   , 1.269, 2.   , 1.349,
       1.952, 1.804, 1.871, 1.853, 1.992, 1.862, 2.   , 1.45 , 2.   ,
       1.089, 1.464, 1.011, 1.371, 1.001, 1.611, 1.341, 1.174, 1.012,
       1.076, 1.627, 1.266, 1.812, 2.   , 1.031, 1.675, 1.273, 1.093,
       2.   , 1.874, 1.281, 1.974, 1.043, 1.526, 2.   , 1.264, 1.153,
       1.01 , 1.893, 1.988, 1.42 , 1.284, 1.727, 2.   , 2.   , 1.93 ,
       1.789, 2.   , 1.084, 1.984])

输出:

array([1., 2., 1., 2., 1., 2., 1., 2., 1., 2., 2., 2., 2., 2., 2., 2., 1.,
       2., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 2., 2., 1., 1.,
       1., 1., 2., 2., 1., 2., 1., 1., 2., 1., 1., 1., 2., 2., 1., 1., 2.,
       2., 2., 2., 2., 2., 1., 2.])

子题: 我目前使用的方法只适用于范围为 1 的数字集。是否有一种方法只检查小数位,因此也适用于更多不同的集?

使用np.divmod分隔每个元素中的整数和分数。然后使用您的方法舍入小数部分并重新组合:

>>> arr = np.array([0.6, 0.8, 1.6, 1.8, 2.6, 2.8])
>>> rnd_lim = 0.7
>>> whole, frac = np.divmod(arr, 1)
>>> rounded_fracs = np.where(frac.__ge__(rnd_lim), frac,np.floor(frac))
>>> rounded_fracs = np.where(rounded_fracs.__lt__(rnd_lim), rounded_fracs, np.ceil(rounded_fracs))
>>> rounded_fracs + whole
array([0., 1., 1., 2., 2., 3.])