-4

It seems like there is a difference in modulo operator answers depending on a programming language. For example, c++, c, and Java all return -1 for an expression like -5%2 while python3.x outputs 1 for the same calculation. Why is this the case?

Edit: mistakenly wrote -10%2 instead of -5%2.

  • In this question c and c++9 are using printf("%d"), Java is using sout() and python is using print() – oculisExemplumRotam Feb 04 '20 at 03:46
  • 7
    uh, that should be 0 in all languages – ikegami Feb 04 '20 at 03:48
  • Putting the problems in the question aside: in Python the signature of the result depends on the signature of the second operand. – Klaus D. Feb 04 '20 at 03:50
  • 1
    There is no modulo operator in Java. It is a remainder operator. That alone is sufficient to answer your question. – user207421 Feb 04 '20 at 04:11
  • *"Why is this the case?"* Because the designers of Python decided not to follow the precedent set by C, while the designers of Java decided to stay with the precedent (on a lot of Java's features, actually). – Andreas Feb 04 '20 at 04:12
  • At least for C++ and Python (3), it returns `0`, **as expected** (I did not test it for other languages but I guess it should be same). – Fareanor Feb 04 '20 at 08:46
  • Regarding the response of Marquis of Lorne on Feb 4, the Marquis has the best answer. You can see that the results for Java are for the remainder operation as described in the documentation for MATLAB. Check out the difference in the rem()) and mod() functions. The documentation also supplies a nice one line algorithm for each of these functions. – Garrett A. Hughes Sep 07 '20 at 15:20

1 Answers1

0

The behaviour of mod is different depending on the language you are using, and which implementation of mod you are using in that language.

List of behaviours here: https://en.wikipedia.org/wiki/Modulo_operation#In_programming_languages

In your case, the results of the % in python takes the sign of the divisor.

>>> 11%-2
-1
>>> -11%2
1

But math.fmod is the opposite.

>>> import math
>>> math.fmod(11,-2)
1.0
>>> math.fmod(-11,2)
-1.0

Java is the opposite way around. % uses the dividend and fmod uses the divisor.

Loocid
  • 6,112
  • 1
  • 24
  • 42