7

Below is some code in C++. If you try something like -2%5 in python the result is positive 3 while many other languages like c++ C# (code) and flash give -2

Why do they give -2 and is one version more correct than the other?

#include <cstdio>
int main(){
printf("%d\n", 2%5);
printf("%d\n", -2%5);
printf("%d\n", -2%77);
printf("%d\n", 2%-77);
printf("%d\n", -2%-77);
}

Output:

2
-2
-2
2
-2
vikki
  • 2,766
  • 1
  • 20
  • 26

3 Answers3

7

If r = a % n, then a = n * q + r for some q. That means that you have many choices for the value of r, depending on the value of q that gets chosen.

I'd recommend reading http://en.wikipedia.org/wiki/Modulo_operation, which says that most programming languages choose r with -n < r < n. That means that, unless r is zero, you have two choices for the value of r - one positive, one negative. Different programming languages make different decisions about whether to take the positive or negative one. You'll find a table on that page that summarizes what different languages do:

  • Python chooses r with the same sign as n (which is what you see above).
  • C++ 2011 chooses r with the same sign as a (and before the 2011 standard, it's implementation defined).

If you want to be sure that you get the positive one in Python, use this:

r = a % n
if r < 0:
  r += n
jamylak
  • 128,818
  • 30
  • 231
  • 230
thomson_matt
  • 7,473
  • 3
  • 39
  • 47
2

According to the C++ documentation:

For negative values, the result may vary depending on the library implementation.

Which seems odd. The Python documentation says only this:

The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand.

It seems to me that the Python way is more logical, but that's just a gut feeling.

Oldskool
  • 34,211
  • 7
  • 53
  • 66
  • 1
    It's implementation defined in C++98 (and C-90). It is well-defined in C++11 (and C-99): The sign of the result of the modulus operator is the same as the sign of the dividend. In Python, the result has the same sign as does the divisor. Which way to interpret things is a bit of a coin toss. What makes most sense to me is the languages that provide both implementations so I as the programmer can choose the one that makes more sense in some particular context. – David Hammen Feb 17 '12 at 09:55
-1

I think you should look at the below. In addition to using slightly different algorithms, operator precedence matters. Try it with brackets:

In [170]: 2%5
Out[170]: 2

In [171]: -2%5
Out[171]: 3

In [172]: (-2)%5
Out[172]: 3

In [173]: -(2%5)
Out[173]: -2
Marcin
  • 48,559
  • 18
  • 128
  • 201