0

I was surprised to learn that np.round(item, decimals=0) rounds 14.50 down to 14. I understand this is linked to the number of decimal point but I'm not sure why.

How can I ensure that number like 14.50 is always rounded up 15?

script:

myval = 14.50
np.round(myval, decimals=0)

output:

14.0
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
Boosted_d16
  • 13,340
  • 35
  • 98
  • 158

5 Answers5

3

numpy rounds to even, that means, that if the fractional part is exactly 0.5 the number is rounded up, if the whole part is odd and rounded down, if the whole part is even.

Daniel
  • 42,087
  • 4
  • 55
  • 81
3

From the documents on the equivalent function np.around:

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 [R9] and errors introduced when scaling by powers of ten.

For this reason, np.round takes 14.5 back down to 14, not up to the odd number 15.

If you just want to round up to an integer, you could use np.ceil instead:

>>> np.ceil(14.5)
15.0
Alex Riley
  • 169,130
  • 45
  • 262
  • 238
3

If you're using 2.x the default python round function should do what you want for positive floats.

   >>> round(14.5)
   15.0

   >>> round(14.49)
   14.0

Not sure what best practices are but this works for a dataframe and python 2.x:

df = pd.DataFrame([1.5,2.5,3.5])
rounded_df = df.applymap(round)

Note python 2.x's round rounds away from zero so it will round negative numbers down.

Clyde
  • 171
  • 8
1

In Python, if the fractional component of the number is halfway between two integers, one of which is even and the other odd, then the even number is returned.

This kind of rounding is called rounding to even (or banker’s rounding). It is the case because if we always round 0.5 up to the next largest number, then the average of a large data set rounded numbers is likely to be slightly larger than the average of the unrounded numbers: this bias or drift can have very bad effects on some numerical algorithms and make them inaccurate.

0

I know this is an old question but I think I also have an answer that will do what you desire.

You can use this:

>>> np.int32(14.5+0.5)
15
mj1261829
  • 1,200
  • 3
  • 26
  • 53