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.
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.
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.
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;-).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With