Rounding a number to nearest even
bdsatish
bdsatish at gmail.com
Fri Apr 11 07:32:13 EDT 2008
On Apr 11, 4:24 pm, cokofree... at gmail.com wrote:
> On Apr 11, 1:19 pm, cokofree... at gmail.com wrote:
>
> > couldn't you just do.
>
> > #untested
> > new_round(n):
> > answer = round(n)
> > # is answer now odd
> > if answer % 2:
> > return answer - 1
> > else:
> > return answer
>
> Whoops, this also affects odd numbers...
>
> Will try and find a GOOD solution later...
>
> Strange request though, why do you need it that way, because 2.5 is
> CLOSER to 3 than to 2...
It also fails for negative numbers. For -2.5 as input, I get -4.0
whereas I expect -2.0
This is a lengthy solution I came-up with:
def round_even(x):
temp = round(abs(x))
if (abs(x) - 0.5)%2.0 == 0.0: temp=temp-1
return signum(x)*temp
def signum(x):
if x>0: return 1
if x<0: return -1
return 0
But i guess there are better ways. I need it 'cos I'm translating some
code from Mathematica to Python. And Math..ica's Round[ ] behaves this
way (as I requested)
More information about the Python-list
mailing list