correct round of reals?

Fredrik Lundh fredrik at
Fri May 12 13:27:10 CEST 2000

Peter Schneider-Kamp <petersc at> wrote:
> I have put the rint(3) function in the math module. As
> Guido observed this is not an ANSI C function and not
> available on every platform. Now I want to "simulate"
> rint on those insane platforms. What is the Right Way(TM)
> to do it?
> I have written
>   double myrint(x) double x; {
>     return floor(x+0.5);
>   }
> so far, but that does not seem to exhibit the same
> behaviour. Problems with this definition:
> myrint(2.5) gives 3.0, not 2.0 as rint(3)
> myrint(3.5) gives 4.0 as expected
> IEEE standard seems to be rounding towards the next
> even integer in .5-cases. How do I do that?

how about:

def rint(v, m=4503599627370496.0):
    if abs(v) > m:
        return v
    if v > 0:
        return (v + m) - m
        return (v - m) + m

(this assumes IEEE doubles)


More information about the Python-list mailing list