Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly round-up half float numbers?

I am facing a strange behavior of the round() function:

for i in range(1, 15, 2):     n = i / 2     print(n, "=>", round(n)) 

This code prints:

0.5 => 0 1.5 => 2 2.5 => 2 3.5 => 4 4.5 => 4 5.5 => 6 6.5 => 6 

I expected the floating values to be always rounded up, but instead, it is rounded to the nearest even number.

Why such behavior, and what is the best way to get the correct result?

I tried to use the fractions but the result is the same.

like image 557
Delgan Avatar asked Oct 08 '15 15:10

Delgan


People also ask

How do you round up half float numbers in Python?

In Python, rounding half up strategy can be implemented by shifting the decimal point to the right by the desired number of places. In this case you will have to determine whether the digit after the shifted decimal point is less than or greater than equal to 5.

How do you round up a float?

Option 1: Python Round Function Python has an inbuilt function round(), which will take the float value and round it off. The round() function takes two parameters: Number and Ndigits (optional). Ndigits represent the number of decimal places to round.

How do you round a half number?

When rounding to the nearest half, round the fraction to whichever half the fraction is closest to on the number line. If a fraction is equally close to two different halves, round the fraction up.

Do you round .5 up or down?

There are certain rules to follow when rounding a decimal number. Put simply, if the last digit is less than 5, round the previous digit down. However, if it's 5 or more than you should round the previous digit up. So, if the number you are about to round is followed by 5, 6, 7, 8, 9 round the number up.


1 Answers

The Numeric Types section documents this behaviour explicitly:

round(x[, n])
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.

Note the rounding half to even. This is also called bankers rounding; instead of always rounding up or down (compounding rounding errors), by rounding to the nearest even number you average out rounding errors.

If you need more control over the rounding behaviour, use the decimal module, which lets you specify exactly what rounding strategy should be used.

For example, to round up from half:

>>> from decimal import localcontext, Decimal, ROUND_HALF_UP >>> with localcontext() as ctx: ...     ctx.rounding = ROUND_HALF_UP ...     for i in range(1, 15, 2): ...         n = Decimal(i) / 2 ...         print(n, '=>', n.to_integral_value()) ... 0.5 => 1 1.5 => 2 2.5 => 3 3.5 => 4 4.5 => 5 5.5 => 6 6.5 => 7 
like image 87
Martijn Pieters Avatar answered Nov 09 '22 00:11

Martijn Pieters