This question is about numpy.rint
, which by definition rounds to the nearest integer. However, the following code produces inconsistent results.
In [1]: import numpy as np
for i in range(5, 105, 10):
print(i, np.rint(i/10))
Out[1]: 5 0 # Should be 1
15 2 # Correct
25 2 # Should be 3
35 4 # Correct
45 4 # Should be 5
55 6 # Correct
65 6 # Should be 7
...
So there appears to be a pattern: if, after division by 10, the units place is even, the number is rounded down, but if the units place is odd, the number is rounded up. However, according to rounding rules, the units place should not matter!
Either numpy
should use the "round half up", that is, exactly at half, it rounds up to the next integer, or it should use the "round half down". It cannot do both, and be inconsistent.
Normally, I would open a bug report with numpy
for this, but I am not sure if this is entirely numpy
being weird, or some underlying quirk of how python interprets floating points, or due to loss of precision from conversion to binary and back.
Note that numpy.round(i, 0)
also behaves the same.
A fix is to add a small fraction after the division by 10: numpy.rint(i/10 + 0.1)
, and the answers come correct.