floor and ceil with number of decimals
This seems to work (needs no import and works using the // operator which should be faster than numpy, as it simply returns the floor of the division):
a = 2.338888
n_decimals = 2
a = ((a*10**n_decimals)//1)/(10**n_decimals)
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)