6 ms·
I was surprised by the observation that Python rounds towards even numbers, so round(0.5) = 0, but round(1.5) = 2. This is indeed clearly documented [1], I gue
by arraypad 4y ago
I was surprised by the observation that Python rounds towards even numbers, so round(0.5) = 0, but round(1.5) = 2.
This is indeed clearly documented [1], I guess I never looked closely enough. I found some discussion on the dev-python list [2] which shows at least I'm not the only one surprised by this!
[1] https://docs.python.org/3/library/functions.html#round https://docs.python.org/3/library/functions.html#round
[2] https://groups.google.com/g/dev-python/c/VNf8TABiB9k https://groups.google.com/g/dev-python/c/VNf8TABiB9k
- masklinn 4y agoThe biggest annoyance with P3’s round is that you can’t specify a rounding mode. Well that and it returns an integer when rounding to 0 digits, but that’s less of an issue since the langage also switched to “true division”.
- dec0dedab0de 4y agoYou can specify a rounding mode if you use decimals instead of floats
- cm2187 4y agoThat's good to know and kind of dangerous. I have seen banking regulators getting upset in the past because of roundings not following the usual convention ("banker's rounding"). You will have a hard time explaining it's an unexpected behaviour of some programming language rather than the management of the bank trying to be cute with the numbers.
- masklinn 4y ago> I have seen banking regulators getting upset in the past because of roundings not following the usual convention ("banker's rounding"). That… is exactly the behaviour python implements, and what GP was surprised by… It is also, incidentally, the IEEE 754 recommendation. Python 2 used to round away from 0.
- cm2187 4y agoOk sorry, I think that's me misinterpreting what banker's rounding mean. But I know the regulator will expect round(0.5) = 1, not 0.
- masklinn 4y agoBanker's rounding is "round to even", because it limits the amount of bias introduced by the rounding. > But I know the regulator will expect round(0.5) = 1, not 0. That's not necessarily the most helpful, as there's at least two tie-breakings which provide that, but differ in their treatment of negative numbers (round up or round to +∞, and round away from zero or round to ∞).
- rubicks 4y agoI have seen banking regulators getting upset because they (effectively) assumed infinite precision until the "final rounding" (their verbiage). This was at a major financial services provider with exactly zero numerical stability analysts. So, consider the source of the complaint.