I\'ve found some strange behaviour in Python regarding negative numbers:
>>> -5 % 4
3
Could anyone explain what\'s going on?
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.