Python 2 or 3, it's normal. When dividing, positive numbers round towards zero while negative numbers round away from zero:
Code:
>>> 10 // 3
3
>>> -10 // 3
-4
Resulting in the numbers you've been getting since
10/3=3.33333333333 and
10-3*3=1 while
-10/3=-3.33333333333 and
-10-(-4*3)=2.
Perl does the same:
Code:
print 10 % 3;
1
print -10 % 3;
2
Check
this blog post to see Guido van Rossum's explanation.
If you need the more usual Euclidean division method you've been used to since school (also used in C), use
math.fmod instead of the
% operator:
Code:
>>> import math
>>> math.fmod(10,3)
1.0
>>> math.fmod(-10,3)
-1.0
As you can also notice, now the sign follows the dividend while it followed the divisor when using the
% operator.