-1

You might consider this question as a duplicate of Python Rounding Inconsistently.

However I still think that there is a justification to emphasise this Python behaviour with it.


While using Python to prepare test data for a C program, I have found this strange behaviour of Python. The rounding of 'halves' come out in pairs!

Can anybody please provide an explanation?

Positive:

>>> round (0.5)
0
>>> round (1.5)
2
>>> round (2.5)
2
>>> round (3.5)
4
>>> round (4.5)
4
>>> round (5.5)
6
>>> round (6.5)
6

Negative:

>>> round(-0.5)
0
>>> round(-1.5)
-2
>>> round(-2.5)
-2
>>> round(-3.5)
-4
>>> round(-4.5)
-4
>>> round(-5.5)
-6
>>> round(-6.5)
-6
>>> round(-7.5)
-8
>>> round(-8.5)
-8
ishahak
  • 6,585
  • 5
  • 38
  • 56
  • The current dup target is not correct, but the question is still a duplicate. [See here](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior). – MB-F Mar 12 '18 at 13:50
  • ok that's sounds better. I still think that there is room for titling it as a strange behaviour so that programmers will take attention – ishahak Mar 12 '18 at 13:54
  • Yep, that's the reason of marking duplicates - people can find them and they serve as sign posts to a single canonical answer. (Duplicate does not mean the question is bad. On the contrary, it may help others who look for the same terms.) – MB-F Mar 12 '18 at 14:01

1 Answers1

1

This is a very common rounding method, called Banker’s Rounding: if a number is right in the middle, it rounds to the next even number, not down, as the standard rounding does.

This is useful to reduce accumulation of rounding errors; with Banker’s Rounding, the errors have a better chance to even out over many transactions, instead of accumulating continuously.

Aganju
  • 6,295
  • 1
  • 12
  • 23
  • Thank you the answer! I find it very annoying that a programming language takes such a high-level decision within its core functionality. I'm actually quite socked by that! – ishahak Mar 12 '18 at 13:50