Rounding a number to nearest even

colas.francis at gmail.com colas.francis at gmail.com
Fri Apr 11 08:43:42 EDT 2008


On 11 avr, 14:14, Gerard Flanagan <grflana... at gmail.com> wrote:
> On Apr 11, 2:05 pm, Gerard Flanagan <grflana... at gmail.com> wrote:
>
> > On Apr 11, 12:14 pm, bdsatish <bdsat... at gmail.com> 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 ?

> In fact you can avoid the call to the builtin round:

Alternatively, you can avoid the test using both divmod and round:

In [55]: def myround(x):
   .....:     d, m = divmod(x, 2)
   .....:     return 2*d + 1 + round(m-1)
   .....:

In [58]: assert myround(3.2) == 3

In [59]: assert myround(3.6) == 4

In [60]: assert myround(3.5) == 4

In [61]: assert myround(2.5) == 2

In [62]: assert myround(-0.5) == 0.0

In [63]: assert myround(-1.5) == -2.0

In [64]: assert myround(-1.3) == -1.0

In [65]: assert myround(-1.8) == -2

In [66]: assert myround(-2.5) ==  -2.0



More information about the Python-list mailing list