Rounding a number to nearest even

Sjoerd Mullender sjoerd at acm.org
Tue Apr 15 05:22:16 EDT 2008


Thomas Dybdahl Ahle wrote:
> 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)]
> 

No, this does not work:
>>> [(f*.25, evenRound(f*.25)) for f in xrange(0,20)]
[(0.0, 0.0), (0.25, 0.0), (0.5, 0.0), (0.75, 0.0), (1.0, 2.0), (1.25,
2.0), (1.5, 2.0), (1.75, 2.0), (2.0, 2.0), (2.25, 2.0), (2.5, 2.0),
(2.75, 2.0), (3.0, 4.0), (3.25, 4.0), (3.5, 4.0), (3.75, 4.0), (4.0,
4.0), (4.25, 4.0), (4.5, 4.0), (4.75, 4.0)]

x.75 should be rounded up.

-- 
Sjoerd Mullender

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 379 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20080415/6371d8af/attachment-0001.sig>


More information about the Python-list mailing list