Rounding Question

Lloyd Hugh Allen vze2f978 at mail.verizon.net
Fri Feb 23 19:05:56 EST 2001


Remco Gerlich wrote:
> 
> 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)
...
> 
> PS By now his original math.ceil solution starts to look better than mine...

Assuming integers, this'll do the same thing in one line:

>>> def tableDepth(x):
	return 10 * ((x + 9) / 10)

>>> tableDepth(49)
50
>>> tableDepth(40)
40

without integers, though, it'll give a runtime error. Or something.



More information about the Python-list mailing list