Integer division, surprising results

Ralf Muschall ralf at tecont.de
Wed May 12 07:54:01 EDT 2004


"Tim Peters" <tim.one at comcast.net> writes:

> It's primarily driven by the desire that i%j have the same sign as j.  If

That's the side effect, not the desire (AFAIK).

> you want that, and also want
>
>     i == (i/j)*j + (i%j)
>
> then integer division has to return the floor.  C also requres that identity

AFAIK the history is the other way around: The Unix+C-philosophy was
essentially the "don't care"-approach, i.e. '/' does just what the CPU
happens to do if it sees a divide instruction.  Most machines seem to
truncate here, therefore '%' can give negative results.  This rarely
disturbs anyone, since most people don't divide negative numbers.
Those who do (e.g. mathematicians) fall outside the "good for 90% is
good enough"-attitude and have to help themselves.

Scheme and Lisp *do* care (offering both "remainder" (the easily
implemented thing) and "modulo" (the real thing)), as does Python with
its '%'[1].  (Called "rem" and "mod" in Lisp).

[1] I don't know whether it also offers a shortcut for
sign(x)*mod(abs(x),y) for people who insist on the bad result.

Ralf
-- 
GS d->? s:++>+++ a+ C++++ UL+++ UH++ P++ L++ E+++ W- N++ o-- K- w--- !O M- V-
PS+>++ PE Y+>++ PGP+ !t !5 !X !R !tv  b+++ DI+++ D?  G+ e++++ h+ r? y?



More information about the Python-list mailing list