Rounding a number to nearest even

Chris cwitts at gmail.com
Tue Apr 15 05:31:36 EDT 2008


On Apr 15, 11:22 am, Sjoerd Mullender <sjo... at acm.org> wrote:
> 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
>
>  signature.asc
> 1KDownload

even is closer to even.75 than even+1.25.  Why should it be rounded
up ?



More information about the Python-list mailing list