2

Somebody please explain to me why this is happening, I can't seem to find a right answer. And what is the best way to round integers to achieve consistent results?

a = 3.5
b = 2.5

print(f'3.5 rounds up : {round(a)},  2.5 rounds down: {round(b)}')

Output: 3.5 rounds up : 4,  2.5 rounds down: 2

I expected both integers to round down or up the same.

3 Answers3

7

From https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even:

...if the fractional part of x is 0.5, then y is the even integer nearest to x. ... This is the default rounding mode used in IEEE 754 operations for results in binary floating-point formats

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • This is quite helpful, thank you! – Jorge Alvarez Mar 29 '23 at 15:50
  • 1
    More specifically, from the documentation of the `round` function, ["\[...\]; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`)."](https://docs.python.org/3/library/functions.html#round) – chepner Mar 29 '23 at 16:02
0

The numpy floor() / ceil() functions are a great way to round the integers consistently:

import numpy as np
print(np.floor(3.5))
print(np.floor(2.5))
print(np.ceil(3.5))
print(np.ceil(2.5))
windyvation
  • 497
  • 3
  • 13
0

That is because in python, the round function rounds to the nearest even number if two multiples of 10 are equally close. Here's the relevant documentation - https://docs.python.org/release/3.9.5/library/functions.html#round

AishwaryaK
  • 24
  • 3