use*_*317 6 python numpy rounding
我读到 numpy 在四舍五入方面是无偏见的,并且它的工作方式是按照其设计的方式工作的。“如果你总是将 0.5 舍入到下一个最大的数字,那么一组舍入数字的平均值可能会略大于未舍入数字的平均值:这种偏差或漂移会对某些数值算法产生非常不利的影响,并且让他们变得不准确。”
无视这些信息并假设我总是想四舍五入,我该如何在 numpy 中做到这一点?假设我的数组可能很大。
为简单起见,假设我有数组:
import numpy as np
A = [ [10, 15, 30], [25, 134, 41], [134, 413, 51]]
A = np.array(A, dtype=np.int16)
decimal = A * .1
whole = np.round(decimal)
Run Code Online (Sandbox Code Playgroud)
十进制看起来像:
[[ 1. 1.5 3. ]
[ 2.5 13.4 4.1]
[ 13.4 41.3 5.1]]
Run Code Online (Sandbox Code Playgroud)
整体看起来像:
[[ 1. 2. 3.]
[ 2. 13. 4.]
[ 13. 41. 5.]]
Run Code Online (Sandbox Code Playgroud)
如您所见,1.5 四舍五入为 2,2.5 也四舍五入为 2。如何强制始终获得 XX.5 的舍入答案?我知道我可以遍历数组并使用 python round() 但这肯定会慢得多。想知道是否有办法使用 numpy 函数来做到这一点
import numpy as np
A = [ [1.0, 1.5, 3.0], [2.5, 13.4, 4.1], [13.4, 41.3, 5.1]]
A = np.array(A)
print(A)
def rounder(x):
if (x-int(x) >= 0.5):
return np.ceil(x)
else:
return np.floor(x)
rounder_vec = np.vectorize(rounder)
whole = rounder_vec(A)
print(whole)
Run Code Online (Sandbox Code Playgroud)
或者,您还可以查看numpy.ceil、numpy.floor、numpy.trunc以获得其他舍入样式