How does the module work and why is it different from Python than most languages?

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

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

 #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 
+7
source share
3 answers

If r = a % n , then a = n * q + r for some q . This means that you have many options for the r value, depending on the q value selected.

I would recommend reading http://en.wikipedia.org/wiki/Modulo_operation , which says that most programming languages ​​choose r with -n < r < n . This means that if r is zero, you have two options for the value of r - one positive, one negative. Different programming languages ​​make different decisions about whether to accept positive or negative. On this page you will find a table in which different languages ​​are summarized:

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

If you want to be sure you get a positive result in Python, use this:

 r = a % n if r < 0: r += n 
+7
source

According to C ++ documentation :

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

Which seems strange. The Python documentation says only the following:

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

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

+2
source

I think you should look below. Besides using slightly different algorithms, operator precedence matters. Try using 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 
-one
source

All Articles