0

If I do round(4.265,2) it returns 4.26 but if I do round(4.375,2) it returns 4.38.

round(4.265,2)
round(4.375,2)
Answer:
4.26 (Expecting 4.27 instead of 4.26)
4.38

I am expecting output of first round function to be 4.27 just like it is doing it for second round function (4.38). Does anyone knows why python returns different rounded answer?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Prish
  • 605
  • 7
  • 21
  • Found related answer here: https://stackoverflow.com/questions/10093783/rounding-error-in-python-with-non-odd-number/10093820#10093820 It's called 'Banker's rounding'. – Prish Nov 04 '19 at 21:19
  • 1
    Banker's rounding isn't what explains this behaviour. The result is due to the error introduced when converting a numerical literal expressed in decimal to the internal binary floating-point format being used. `4.265` rounds to `4.26` because it's *closer* to 4.26 than to 4.27. – Mark Dickinson Nov 05 '19 at 21:13
  • Thanks @ShadowRanger. I was looking for that duplicate but failing to find it (and finding a lot of answers that tried to explain this away through banker's rounding instead). – Mark Dickinson Nov 05 '19 at 21:28
  • 1
    @MarkDickinson: I'm pretty sure there are other duplicates, that's just the first one I found. I agree it's hard to determine, at a glance, whether a question is covering banker's rounding or floating point representational issues. – ShadowRanger Nov 05 '19 at 21:30

1 Answers1

0

Python uses the Round to Nearest, Ties to Even method of rounding. https://en.wikipedia.org/wiki/IEEE_754-1985#Rounding_floating-point_numbers

Jeff
  • 382
  • 1
  • 7
  • 1
    Note that the "ties to even" bit isn't all that relevant here: `4.265` rounds to `4.26` purely because it's *closer* to `4.26` than to `4.27`, thanks to the usual what-you-see-is-not-what-you-get nature of binary floating-point. The numeric literal `4.265` gives a float whose actual value is `4.26499999999999968025576890795491635799407958984375`, so it's not actually a tie. `4.375` *is* a tie, because `4.375` happens to be exactly representable in binary floating-point, so there the ties-to-even part *does* come into play. For another example, consider `round(2.675, 2)` (which gives 2.67). – Mark Dickinson Nov 05 '19 at 21:10
  • @MarkDickinson Thanks, I updated it. In fact, Python doesn't use 'ties to even' rounding in round(). – Jeff Nov 08 '19 at 14:23
  • `round` uses ties-to-even since Python 3.0. You're correct that Python 2.7 uses ties-away-from-zero. – Mark Dickinson Nov 08 '19 at 14:26