Q: Feature Wish: "%" Extension
tim.one at home.com
Sun Nov 4 08:14:45 CET 2001
> Back when dinasaurs walked the earth, I had a long argument with the
> Pascal standards committe about the correct definition of the modulus
> operator. Believe it or not, they had it so that (-3)%2 was a negative
Most languages do, alas.
> After much going back and forth, I convinced them otherwise. To
> my astonishment, they then proceded to get integer division wrong --
> incompatible with the definition of mod that they finally agreed to! C
> and C++ have it wrong also.
C89 actually allowed 1 or -1 in this case -- it left floor vs truncation
implementation-defined for negative int division results. C99 goes out of
its way to insist on truncation, though; the Rationale only mentions
"compatibility with Fortran", like masses of C programmers give a rip about
> The following relation should hold for any integer x and any positive
> integer M:
> (x/M)*M + (x%M) == x
While C left floor-vs-trunc undefined, it did insist on this (so int / and %
are both right or both wrong in a given C89 implementation).
> That makes "slicing and dicing" work easy to do. Change it, and you
> start needing tests for negative in your code.
Yup! Long before Python 1.0 was released, I badgered <0.6 wink> Guido into
changing Python to do the floor-div + usable-mod business. We both missed
that i/j shouldn't do integer division at all, though (and // is being
introduced for flooring division in 2.2, and int/int will eventually be
changed to return a float or a rational).
An odd thing is that, when this comes up, people complain that under
Python's current rules it's not necessarily the case that
(-i)/j == -(i/j)
Across decades of integer numeric programming, I can't recall any *use* for
that identity; but that i%j >= 0 whenever j>0 is endlessly useful, as is
your identity relating int-div and int-mod.
doing-a-right-thing-is-a-trial-ly y'rs - tim
More information about the Python-list