Modulus operation with negatives values - weird thing?

lurks picture lurks · Sep 4, 2008 · Viewed 11.3k times · Source

Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this?

I've read that in some languages the result can be machine-dependent, but I'm not sure though.

Answer

Konrad Rudolph picture Konrad Rudolph · Sep 4, 2008

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.