Modulus operation with negatives values - weird thing? Modulus operation with negatives values - weird thing? python python

Modulus operation with negatives values - weird thing?


By the way: most programming languages would disagree with Python and give the result -2. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of a and b is the (strictly positive) rest r of the division of a / b. More precisely, 0 <= r < b by definition.


The result of the modulus operation on negatives seems to be programming language dependent and here is a listing http://en.wikipedia.org/wiki/Modulo_operation


Your Python interpreter is correct.One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1).

e.g.:13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3

or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3