Python 2.7.1:
print -34 % 4 # outputs 2
Java 1.5.0:
System.out.println(-34 % 4); // outputs -2
Which is correct? Why the difference?
The wikipedia article on modulo says
When either a or n is negative, this naive definition breaks down and programming languages differ in how these values are defined.
Maybe this isn’t a proper SO question and will get deleted but I’d be interested to see the responses.
It’s just a convention the language has chosen. There is no one choice that is more mathematically correct than another.
Hints for the reasons for Python’s choice can be found in the source: http://hg.python.org/cpython/file/2.7/Objects/intobject.c#l567
Python’s version is the one more commonly used in number theory. The Java version implements the same behavior as C. The Python way is convenient because the sign of the result is always the same sign as the divisor. This means that
x % nalways gives a value in0 <= result < nwhen n is positive.I speculate that the reason a lower level language like C uses a different convention is that it is “closer to the metal” returning the same result as n signed division in machine language (see IDIV for example). If C were to have adopted the number theory convention, it would need to compile additional instructions to compare the sign of the result to the sign of the divisor and if they didn’t match then jump to additional code to add or substract the divisor from the result (IOW, C adopts a convention that corresponds to minimal effort).