Rounding a number to nearest even

bdsatish bdsatish at gmail.com
Fri Apr 11 14:45:58 CEST 2008


On Apr 11, 5:33 pm, bdsatish <bdsat... at gmail.com> wrote:
> HI Gerard,
>
> I think you've taken it to the best possible implementation. Thanks !
> On Apr 11, 5:14 pm, Gerard Flanagan <grflana... at gmail.com> wrote:
>
> > In fact you can avoid the call to the builtin round:
>
> > ------------------------------------------------
>
> > assert myround(3.2) == 3
> > assert myround(3.6) == 4
> > assert myround(3.5) == 4
> > assert myround(2.5) == 2
> > assert myround(-0.5) == 0.0
> > assert myround(-1.5) == -2.0
> > assert myround(-1.3) == -1.0
> > assert myround(-1.8) == -2
> > assert myround(-2.5) ==  -2.0
> > ------------------------------------------------

OK, I was  too early to praise Gerard. The following version:

def myround(x):
     n = int(x)
     if abs(x - n) >= 0.5 and n % 2:
          return n + 1 - 2 * int(n<0)
     else:
          return n

of Gerard doesn't work for 0.6 (or 0.7, etc.) It gives the answer 0
but I would expect 1.0 ( because 0.6 doesn't end in 0.5 at all... so
usual rules of round( ) apply)



More information about the Python-list mailing list