Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between Modulus Implementation in Python Vs Java

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.

like image 735
Cerin Avatar asked Feb 07 '10 00:02

Cerin


People also ask

Is there modulus in Python?

Python supports a wide range of arithmetic operators that you can use when working with numbers in your code. One of these operators is the modulo operator ( % ), which returns the remainder of dividing two numbers. In this tutorial, you'll learn: How modulo works in mathematics.

What is modulus in Java example?

If both operands for %, the modulus operator have type int, then exprleft % exprright evaluates to the integer remainder. For example, 8 % 3 evaluates to 2 because 8 divided by 3 has a remainder of 2.


2 Answers

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

like image 149
Alex Martelli Avatar answered Oct 12 '22 01:10

Alex Martelli


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.

like image 31
Bill the Lizard Avatar answered Oct 12 '22 00:10

Bill the Lizard