views:

755

answers:

4

I've noticed differing implementations of the modulus operator in Python and Java.

For example, in Python:

>>> print -300 % 800
>>> 500

Whereas in Java:

System.out.println(-300 % 800);
-300

This caught me off guard, since I thought something as basic as modulus was universally interpreted the same way. I'm a fan of Python's interpretation (which I presume is borrowed from C), although I see the logic behind Java's implementation.

Which do you typically prefer? Is there any specific reason for the differing interpretations? I have no intention of starting a language war, simply curious.

+4  A: 

I prefer C's interpretation (also used in Python), where % is indeed a modulus operator. Good discussion in the wikipedia page and the links from it (including one bit about why taking instead the sign of the dividend can lead to one silly bug unless one's careful;-).

Alex Martelli
C99 uses the sign of the dividend, C89 is implemention dependent, at least according to the article you linked.
ergosys
+1  A: 

In the C standard, negative modulo is undefined, and many C compilers will give you what Java is giving you. In python though, you will always get a positive number, which is often more useful, because it means you can do modulo addition, and subtraction. If negative modulo were to give you a negative, it would not work properly.

I have no idea what advantages getting a negative number from a modulo has.

Jeffrey Aylesworth
A: 

I prefer x mod n to give numbers between 0 and n-1 or between floor(n/2)-n and floor(n/2); this makes it easiest to do the math in one's head.

As long as everything is equivalent, I don't really care when it comes to languages--though one does have to be aware of the convention.

Incidentally, Java can't quite make up its mind--% on negative integers returns a negative value, the mod method of java.math.BigInteger returns values between 0 and n-1 (inclusive), and the divideAndRemainder method again returns negative values for negative integers.

Rex Kerr
+3  A: 

Now try this:

>>> print 300 % -800
-500

The reason for the difference is that language designers can't seem to decide whether the remainder after division should have the sign of the dividend or the divisor. Some languages don't even specify one or the other, so it's up to the implementer.

There's a list of languages, the operator, and which sign to expect on the Modulo operation Wikipedia page. It's a good place to start, but I usually just run a few simple tests to make sure I know exactly how % is going to behave before I use it in any language I've not tested it in before.

Bill the Lizard