Number Rounding Business

Rounding numbers is probably one of the topics in primary school. In school, we’ve learned that half rounds up, anything less than half rounds down. For example, 0.5 rounds to 1, but 0.4 rounds to 1. Duh, I’m stating the obvious you think. It only came to my attention that this is NOT really the default behaviour in a very popular programming language: Python.

Here, is a simple example to try in your own Python console.

round(0.5, 0)

It gives 0, shocking right? Now try

round(1.5, 0)

You’d think since 0.5 rounds to 0, 1.5 should then round to 1. Nope, it rounds to 2. Why is that? Before you pull your magnifier out to double-check, this is actually a standard conformant behaviour. This is called “rounding half to even” (check this Wikipedia page) and it is the default mode in many programming languages.

To “fix”, or say to have the rounding behaviour of what we were taught in school (nearest integer), Python does provide a built-in library decimal which would allow control of the rounding behaviour. Here is the snippet showing how it could be done.

from decimal import Decimal, ROUND_HALF_UP

def round_half_up(v: float, precision: int = 0) -> float:
    target_precision = "1." + "0" * precision
    rounded = Decimal(str(v)).quantize(Decimal(target_precision), ROUND_HALF_UP)
    return float(rounded)

print("0.5 rounds to ", round_half_up(0.5))
print("1.5 rounds to ", round_half_up(1.5))
print("1.005 rounds to {:.2f}".format(round_half_up(1.005, 2)))

Out of curiosity, I checked what JavaScript does, it is rounding to the nearest integer. That also appears to be what C/C++ has.

#include <math.h>
#include <stdio.h>

int main() {
    int r = round(0.5);
    printf("rounded to %d\n", r);
    return 0;
}

Why are there so many different ways to round a number? Well, I guess they have their own biases in practice. For example, rounding to the nearest even integer supposedly should offset the cumulative error statistically, however it might appear non-intuitive.

Author: librehat

自由軟體萬歲!

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.