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
1.5 is rounded up while 10.5 is rounded down. Is there a reason for this? Is it just and artifact of the inaccuracy of floats?
Edit
Is there a way to get the desired functionality where n.5 is rounded up i.e. to n+1 for both n = even or odd?
So, this kind of behavior (as noted in comments), is a very traditional form of rounding, seen in the round half to even method. Also known (according to David Heffernan) as banker's rounding. The numpy
documentation around this behavior implies that they are using this type of rounding, but also implies that there may be issues with the way in which numpy
interacts with the IEEE floating point format. (shown below)
Notes ----- For values exactly halfway between rounded decimal values, Numpy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact representation of decimal fractions in the IEEE floating point standard [1]_ and errors introduced when scaling by powers of ten.
Whether or not that is the case, I honestly don't know. I do know that large portions of the numpy
core are still written in FORTRAN 77, which predates the IEEE standard (set in 1984), but I don't know enough FORTRAN 77 to say whether or not there's some issue with the interface here.
If you're looking to just round up regardless, the np.ceil
function (ceiling function in general), will do this. If you're looking for the opposite (always rounding down), the np.floor
function will achieve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With