numpy\'s round int doesn\'t seem to be consistent with how it deals with xxx.5
In [2]: np.rint(1.5)
Out[2]: 2.0
In [3]: np.rint(10.5)
Out[3]: 10.0
<
Numpy uses bankers rounding so .5 is rounded to the nearest even number. If you always want to round .5 up but round .4 down:
np.rint(np.nextafter(a, a+1))
or if you always want to round .5 down and .4 down but .6 up:
np.rint(np.nextafter(a, a-1))
NB this also works with np.around
if you want the same logic but not integers.
>>> a = np.array([1, 1.5, 2, 2.5, 3, 3.5])
>>> np.rint(a)
array([1., 2., 2., 2., 3., 4.])
>>> np.rint(np.nextafter(a, a+1))
array([1., 2., 2., 3., 3., 4.])
>>> np.rint(np.nextafter(a, a-1))
array([1., 1., 2., 2., 3., 3.])
What is happening?
nextafter
gives the next representable number in a direction, so this is enough to push the number off 'exactly' 2.5.
Note this is different to ceil
and floor
.
>>> np.ceil(a)
array([1., 2., 2., 3., 3., 4.])
>>> np.floor(a)
array([1., 1., 2., 2., 3., 3.])