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

Python 2.7.1:

print -34 % 4 # outputs 2 

Java 1.5.0:

 System.out.println(-34 % 4); // outputs -2 

What is right? Why is the difference?

modulo wikipedia article says

If either a or n is negative, this naive definition breaks, and programming languages โ€‹โ€‹differ in how these values โ€‹โ€‹are determined.

This may not be the right SO question and will be removed, but I would be interested to see the answers.

+4
source share
4 answers

This is just a convention chosen by language. There is more than one choice that is more mathematically correct than another.

Hints for Python selection reasons can be found in the source: http://hg.python.org/cpython/file/2.7/Objects/intobject.c#l567

The Python version is the most common in number theory. The Java version implements the same behavior as C. The Python path 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 of 0 <= result < n when n is positive.

I assume that the reason a lower level language such as C uses a different convention is because it is "closer to metal" returns the same result as n signed division into machine language (see IDIV , eg). If C accepted the agreement on number theory, it would have to compile additional instructions to compare the sign of the result with the sign of the divisor and if they did not match, then go to the additional code to add or subtract the divisor from the result (IOW, C accepts the agreement, corresponding to minimal effort).

+6
source

This is because both languages โ€‹โ€‹are programmed.

Java considers the numerator sign when applying the module (%), and Python does not.

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

0
source

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

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

Seriously, however, this is a rather arbitrary choice; one definition is more useful in some cases, and (?) the other is more useful in others. Rejoice that you are working in the language that selected it, and not just the one that is faster on this CPU;)

0
source

In c / C ++, the result is -2. So I think thatโ€™s why Java went a different way. They were very interested in attracting C ++ developers at the beginning.

-1
source

Source: https://habr.com/ru/post/1382635/


All Articles