Hi, everyone
I've found some strange behaviour in python regarding negative numbers:
>>> a = -5
>>> a % 4
3
Could anyone explain what's going on?
Hi, everyone
I've found some strange behaviour in python regarding negative numbers:
>>> a = -5
>>> a % 4
3
Could anyone explain what's going on?
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.
Modulo, equivalence classes for 4:
Here's a link to modulo's behavior with negative numbers. (Yes, I googled it)
There is no one best way to handle integer division and mods with negative numbers. It would be nice if a/b
was the same magnitude and opposite sign of (-a)/b
. It would be nice if a % b
was indeed a modulo b. Since we really want a == (a/b)*b + a%b
, the first two are incompatible.
Which one to keep is a difficult question, and there are arguments for both sides. C and C++ round integer division towards zero (so a/b == -((-a)/b)
), and apparently Python doesn't.