Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The modulo operation on negative numbers in Python

I've found some strange behaviour in Python regarding negative numbers:

>>> -5 % 4
3

Could anyone explain what's going on?

like image 209
facha Avatar asked Oct 21 '22 20:10

facha


People also ask

How does modulo work in Python negative numbers?

Unlike C or C++, Python's modulo operator always returns a number having the same sign as the denominator (divisor) and therefore the equation running on the back will be the following: mod = a — math. floor(a/b) * base.

Does modulo work on negative numbers?

How does modulo work with negative numbers? When only the dividend is negative. When only the divisor is negative. When both the divisor and dividend are negative.

How do you find the positive modulus in Python?

Python Number abs() Method Python number method abs() returns absolute value of x - the (positive) distance between x and zero.


2 Answers

Unlike C or C++, Python's modulo operator (%) always return a number having the same sign as the denominator (divisor). Your expression yields 3 because

(-5) / 4 = -1.25 --> floor(-1.25) = -2

(-5) % 4 = (-2 × 4 + 3) % 4 = 3.

It is chosen over the C behavior because a nonnegative result is often more useful. An example is to compute week days. If today is Tuesday (day #2), what is the week day N days before? In Python we can compute with

return (2 - N) % 7

but in C, if N ≥ 3, we get a negative number which is an invalid number, and we need to manually fix it up by adding 7:

int result = (2 - N) % 7;
return result < 0 ? result + 7 : result;

(See http://en.wikipedia.org/wiki/Modulo_operator for how the sign of result is determined for different languages.)

like image 175
kennytm Avatar answered Oct 24 '22 08:10

kennytm


Here's an explanation from Guido van Rossum:

http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

Essentially, it's so that a/b = q with remainder r preserves the relationships b*q + r = a and 0 <= r < b.

like image 40
Kevin Avatar answered Oct 24 '22 10:10

Kevin