Rounding a number to nearest even

hdante hdante at gmail.com
Fri Apr 11 10:29:31 EDT 2008


On Apr 11, 11:13 am, Ivan Illarionov <ivan.illario... at gmail.com>
wrote:
>
> Shorter version:
> def round3k(x):
>     return x % 1 != 0.5 and round(x) or round(x / 2.) * 2.

 Strangely, a "faster" version is:

def fast_round(x):
    if x % 1 != 0.5: return round(x)
    return 2.0*round(x/2.0)


>
> nums =  [ 0, 2, 3.2, 3.6, 3.5, 2.5, -0.5, -1.5, -1.3, -1.8, -2.5, 0.6,
> 0.7 ]
> rnums = [ 0, 2, 3.0, 4.0, 4.0, 2.0, -0.0, -2.0, -1.0, -2.0, -2.0, 1.0,
> 1.0 ]

 You shouldn't remove assertions in the smaller version. :-P

>
> for num, rnum in zip(nums, rnums):
>     assert even_round(num) == rnum, '%s != %s' % (even_round(num),
> rnum)
>     print num, '->', even_round(num)
>
> It makes sense to add `from __future__ import even_round` to Python
> 2.6.




More information about the Python-list mailing list