Rounding a number to nearest even

Mark Dickinson dickinsm at gmail.com
Fri Apr 11 14:05:00 EDT 2008


On Apr 11, 10:29 am, hdante <hda... at gmail.com> wrote:
>  Strangely, a "faster" version is:
>
> def fast_round(x):
>     if x % 1 != 0.5: return round(x)
>     return 2.0*round(x/2.0)

You should be a little bit careful with the test
x%1 == 0.5 if x might be negative:

>>> x = -0.5 + 2**-54
>>> x      # not an exact half...
-0.49999999999999994
>>> x % 1  # ... and yet x%1 == 0.5
0.5

But for x positive, it should be safe.  And for this
particular application, it turns out that it doesn't
matter: it gives the right result for this input anyway.

Mark



More information about the Python-list mailing list