I\'ve found some strange behaviour in Python regarding negative numbers:
>>> -5 % 4
3
Could anyone explain what\'s going on?
As pointed out, Python modulo makes a well-reasoned exception to the conventions of other languages.
This gives negative numbers a seamless behavior, especially when used in combination with the //
integer-divide operator, as %
modulo often is (as in math.divmod):
for n in range(-8,8):
print n, n//4, n%4
Produces:
-8 -2 0
-7 -2 1
-6 -2 2
-5 -2 3
-4 -1 0
-3 -1 1
-2 -1 2
-1 -1 3
0 0 0
1 0 1
2 0 2
3 0 3
4 1 0
5 1 1
6 1 2
7 1 3
%
always outputs zero or positive*//
always rounds toward negative infinity* ... as long as the right operand is positive. On the other hand 11 % -10 == -9