Skip to content
Prev 393442 / 398500 Next

Integer division

Lack of consensus:
  I should mention Python's // operator, which does
  flooring division.
  I should mention Common Lisp, where (floor - -),
  (ceiling - -), (round - -), and (truncate - -)
  all return a quotient and appropriate remainder.
  I should mention Smalltalk, where // and \\ are
  flooring quotient and remainder and quo: and rem:
  are truncating quotient and remainder.
  I should give dishonourable mention to certain
  programming languages where the quotient and remainder
  operators do not actually fit together.

Why the lack of consensus:
  It starts with the fact that there wasn't an agreed
  *mathematical* definition.  Number theorists, as a
  rule, don't care about negative numbers all that much.
  To the extent that they do care, x mod y has to go
  around in neat cycles, which flooring division does
  satisfy and truncating division does not.

  It then goes on to early computers which used sign-and-
  magnitude or ones-complement representation.  In those
  computers, truncating division was the *obvious* thing
  to do.  It also had the nice property that
  n / (2**k) was the same thing as an arithmetic right
  shift by k bits.  And then twos-complement became
  popular.  And not only is the twos-complement range
  asymmetric (so that x might be representable but -x not)
  but arithmetic right shifts aren't the same as truncating
  division any more.  Whoops!

  And then, although flooring division still made sense for
  twos-complement but truncating division didn't really,
  new programming languages kept on specifying truncating
  division because the programming languages of the 1960s
  for the hardware of the 1960s did so.  So new hardware
  designers supported the new programming languages without
  supporting the *reasons* why truncating division had been
  used.
[1] 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3

Think about for example histogramming a collection of
integers by their remainders and what would happen with
truncating remainder.
On Tue, 20 Dec 2022 at 19:53, G?ran Brostr?m <gb at ehar.se> wrote: