Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulus operation with negatives values - weird thing?

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.

like image 961
lurks Avatar asked Sep 04 '08 13:09

lurks


People also ask

How does modulus work with negative numbers?

The modulus of a negative number is found by ignoring the minus sign. The modulus of a number is denoted by writing vertical lines around the number. Note also that the modulus of a negative number can be found by multiplying it by −1 since, for example, −(−8) = 8.

Can modulus give negative value?

These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results.

Is modulus of a negative number positive?

Therefore, the modulus of a number is always positive.


1 Answers

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.

like image 53
Konrad Rudolph Avatar answered Oct 14 '22 09:10

Konrad Rudolph