Integer division and remainder

Paul Rubin phr-n2001 at
Wed Aug 15 01:20:57 CEST 2001

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.

More information about the Python-list mailing list