Neither Python built-in nor numpy's version of ceil/floor support precision.
One hint though is to reuse round instead of multyplication + division (should be much faster):
def my_ceil(a, precision=0):
return np.round(a + 0.5 * 10**(-precision), precision)
def my_floor(a, precision=0):
return np.round(a - 0.5 * 10**(-precision), precision)
UPD:
As pointed out by @aschipfl, for whole values np.round
will round to the nearest even, which will lead to unexpected results, e.g. my_ceil(11)
will return 12. Here is an updated solution, free of this problem:
def my_ceil(a, precision=0):
return np.true_divide(np.ceil(a * 10**precision), 10**precision)
def my_floor(a, precision=0):
return np.true_divide(np.floor(a * 10**precision), 10**precision)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…