Rounding a number to nearest even

Thomas Dybdahl Ahle lobais at gmail.com
Mon Apr 14 14:02:48 EDT 2008


On Fri, 2008-04-11 at 03:14 -0700, bdsatish wrote:
> The built-in function round( ) will always "round up", that is 1.5 is
> rounded to 2.0 and 2.5 is rounded to 3.0.
> 
> If I want to round to the nearest even, that is
> 
> my_round(1.5) = 2        # As expected
> my_round(2.5) = 2        # Not 3, which is an odd num
> 
> I'm interested in rounding numbers of the form "x.5" depending upon
> whether x is odd or even. Any idea about how to implement it ?

This seams to work fine:
evenRound = lambda f: round(f/2.)*2

>>> [(f*.5, evenRound(f*.5)) for f in xrange(0,20)]
[(0.0, 0.0),(0.5, 0.0),
(1.0, 2.0), (1.5, 2.0), (2.0, 2.0), (2.5, 2.0),
(3.0, 4.0), (3.5, 4.0), (4.0, 4.0), (4.5, 4.0),
(5.0, 6.0), (5.5, 6.0), (6.0, 6.0), (6.5, 6.0),
(7.0, 8.0), (7.5, 8.0), (8.0, 8.0), (8.5, 8.0),
(9.0, 10.0), (9.5, 10.0)]

-- 
Best Regards,
Med Venlig Hilsen,
Thomas




More information about the Python-list mailing list