Alex Rivera | Logout

Difference Between Modulus Implementation in Python Vs Java

Asked 2010-02-07T00:16:41.610
18

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.

Edit
Report

1 Answer

6

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;-).

answered 2010-02-07T00:20:43.100

Your Answer