Integer division and remainder

John Roth johnroth at
Wed Aug 15 20:42:20 CEST 2001

"Paul Rubin" <phr-n2001 at> wrote in message
news:7x3d6ui5ye.fsf at
> I've just started reading/playing with Python and I notice that
> integer division and remainder in python works differently than in
> most languages.  In python, division always returns the floor,
> i.e. non-integer quotients are always rounded downwards, towards
> negative infinity:
>    7 / 3 =  2
>   -7 / 3 = -3
> This is kind of strange.  Normally you expect (-a)/b to be the same
as -(a/b).
> That's what happens in most languages, where division rounds towards zero:
>   7 / 3 =  2
>  -7 / 3 = -2
> I think the motivation was so that % would work as a "mod" function
> instead of the more normal "remainder" function.
> Python:  -7 % 3 = 2
> Most other languages: -7 % 3 = -1
> The mod operation is useful for many things, but I think assigning it to %
> in Python shows some confusion in Python.  The result of % is an ordinary
> integer, not an integer mod N.
> I think it would have been better to leave / and % alone, and define
> a new pair of operators (maybe /_ and %_) to implement what Python does.
> That's similar to Common Lisp, which provides the trunc-mod and floor-mod
> functions to implement remainder and modulus respectively.  I don't
> remember if CL has a floor-div function, but it might as well.

I agree with the desire to have two separate operators. As far as I'm
the "mathematically correct" result of the division of two integers is a
(and I'm not going to argue with the BDFL's decision to make it a float -
we don't have rational arithmetic yet, it seems like a reasonable decision.)

The "correct" integer results of integer division are whatever the
application needs.
This has been beaten to death before, so I'm not going to expand on it.

What I would like to see some thought on, however, is how to steer relative
newcomers to the correct operator for their application, without having them
trip over "but it worked this way in language 'x'", or "this is the way Mrs.
taught me in 4th grade." (That last is not a joke - I've had it happen in
classes I've

The only solution I've been able to come up with is "div0," "divf", "rem0"
and "remf" for the
division and remainder operators that round toward zero (div0 and rem0) and
toward negative infinity (divf and remf). In other words, / and % always
return a float
(or a rational, whenever that is implemented), and the word operators are
required if
one wants an integer result. This looks ugly, but at least the words are
more suggestive
than the symbols.

In the direction of suggestive, possibly idiv0, idivf, irem0 and iremf would
be even more
suggestive - they indicate that the result is an integer. Likewise, divmod
would become
idivmod0(,) and idivmodf(,).

Following a comment elsewhere in the thread, adding int0() and intf()
functions would
complete the set.

John Roth

More information about the Python-list mailing list