Question

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.

Was it helpful?

Solution

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 % n always gives a value in 0 <= result < n when 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).

OTHER TIPS

It is because how the both languages are programmed.

Java considers the sign of the numerator when applying modulus (%) operator and Python does not.

If you write "-" sign with the denominator, even Java will ignore it.

Why doesn't the % operator work the same in Python and Java?

Simple: because Python is not Java, and one of the ways in which they differ is the one you quoted from the Wikipedia article. :)

Seriously, though, it's a pretty arbitrary choice; one definition is more useful in some cases and the(?) other is more useful in others. Be glad you're working in a language that picked one, instead of just going with whatever's fastest on that CPU ;)

In c/c++ the result is -2. So I would guess that is why Java went the other way. They were very interested in attracting C++ devs in the beginning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top