Rounding Question

Remco Gerlich scarblac at pino.selwerd.nl
Thu Feb 22 19:52:06 EST 2001


Mikael Olofsson <mikael at isy.liu.se> wrote in comp.lang.python:
> I corrected Remco:
>  >  I'm sorry, but this also behaves badly. It rounds 10 up to 20. To get
>  >  Jacob's desired functionality, you could modify your idea to
>  >  
>  >    rounded = number-((number-1)%10)+9
>  >  
>  >  still assuming only integer input.
> 
> 
> Alex Martelli wrote:
>  >  ...which of course is totally equivalent to the earlier
>  >  proposed
>  >      rounded = (number+9) - ((number+9)%10)
>  >  since addition is commutative and associative (you can
>  >  move the +9 from the right of the expression) AND so
>  >  is addition in modulo-arithmetic, so that:
>  >  
>  >  (X-1)%N==(X%N)+((-1)%N)==(X%N)+((N-1)%N)==(X+N-1)%N
> 
> Of course! I just couldn't stay silent when Remco stumbled again.

Yeah yeah, rub it in... :)

Thing is I wasn't assuming integers, I wanted to write something that works
on floats as well. He only gave integer examples, but his example code with
math.ceil and dividing by 10.0 works on floats as well, and I thought it
likely that he'd get non-integer depth measurements once.

Therefore, I didn't want to use the /10*10 trick and using +9 didn't enter
my mind...

So now I'm proposing, for float input,

if number % 10 == 0:
   return number
else return number+10-(number%10)

Otherwise you'll have to find out what the highest float smaller than 10 is.

Since it is, again, far too late to be posting, I know full well that I'll
get it wrong again...

-- 
Remco Gerlich

PS By now his original math.ceil solution starts to look better than mine...



More information about the Python-list mailing list