How would you safely round a floating point number to the nearest integer ? Python has the built in function round
, but it returns a floating point number
>>> round(4.9)
5.0
>>> help(round)
Help on built-in function round in module __builtin__:
round(...)
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
Using int(round(x))
to obtain the nearest integer looks like a bad idea because the int()
function is discontinuous near integer values, and therefore, round(x)
returns a value wich is very close to a point of discontinuity of int
:
>>> int(4.999999999999999)
4
>>> int(4.99999999999999999999)
5
I designed the following function, which is guaranteed to be stable (except near half integers, the natural points of discontinuity of the function 'nearest integer'):
def iround(x):
"""iround(number) -> integer
Round a number to the nearest integer."""
return int(round(x) - .5) + (x > 0)
Here are a few calls
>>> iround(4.9)
5
>>> iround(5.1)
5
>>> iround(-4.9)
-5
>>> iround(-5.1)
-5
Now, it turns out that for every value that I tried on my computer, iround
returns exactly the same value as int(round(x))
. To see it I wrote a function for the difference
def diff(x):
return int(round(x)) - iround(x)
My question is: does the diff function above always return 0 for every floating value of x on any computer, and is there something in the implementation of the builtin round function which guarantees stability for int(round(x))
? This does not seem to be documented in the official doc. What do you think of this ?