Why do so many computer programming language implementations have trouble with the remainders of negative integers?

504 Views Asked by At

As most of us know, or should know, $-7 \equiv 1 \pmod 4$.

But if you use Java's modulus operator %, you get -3 for the answer, not 1. That's technically correct, but it can cause problems if you're not aware of this as you write a program. C# and Javascript are the same way.

Worse, there are varieties of BASIC which will give you the remainder of the absolute value, e.g., 3 for the example of $-7$; that's clearly wrong.

It looks like only Maple and Mathematica (and by extension, Wolfram Alpha) know better.

Why is this?

3

There are 3 best solutions below

1
On BEST ANSWER

I believe that the primary justification for this is that division in these languages generally rounds towards 0 instead of towards -infinity when doing integer division (questionably) and they want to preserve the identity that (a // b) * b + (a mod b) = a (rightly). From a mathematical standpoint I completely agree that a mod b should always be in [0, b) and do question the original justification for this decision, however for compatibility it is unreasonable to try and change the standard now. Note that there are other languages beyond the ones you have mentioned, such as Python which do behave in this way.

0
On

Let there be given integers $m \lt 0$ and $b \gt 0$.

Proposition: There exist unique integers $q$ and $r$ satisfying the following conditions:

$\quad q \le 0$

$\quad0 \le -r \lt b\;$ (so $r$ is a nonpositive integer)

$\quad m = qb + r$

The proof is left as an exercise for the interested reader.

If you are working with mixed numbers/improper fractions, this might float your boat; see How to Convert a Negative Mixed Number Into an Improper Fraction : Fractions 101. So $-7/4 = -1 \frac{3}{4}$, and some might insist that $-7 \equiv -3 \pmod 4$ make sense.

0
On

Hint: The paper The Euclidean Definition of the Functions $\mathrm{div}$ and $\mathrm{mod}$ by R.T. Boute provides an in-depth discussion of different definitions in mathematics and programming languages.

I'm a great fan of D.E. Knuth and since his F-definition (flooring the quotient and rounding toward negative infinity) is addressed in the paper as one of two preferred approaches, I also recommend reading section 3.4 '$\mathrm{MOD}$' - THE BINARY OPERATION in Concrete Mathematics.