Rounding Question

Alex Martelli aleaxit at yahoo.com
Thu Feb 22 03:43:14 EST 2001


"Mikael Olofsson" <mikael at isy.liu.se> wrote in message
news:XFMail.010222082319.mikael at isy.liu.se...
On 21-Feb-01 Remco Gerlich wrote:
 >  I'd go for
 >  rounded = number-(number%10)+10
 >  now.

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.


...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


Alex






More information about the Python-list mailing list