Here is the proof:
-8 == -2 * 3 - 2
that means -8%3
should be equal to -2
.
but python returns 1
and it's driving me crazy
Here is the proof:
-8 == -2 * 3 - 2
that means -8%3
should be equal to -2
.
but python returns 1
and it's driving me crazy
In python, the sign matches the denominator.
>>> -8 % 3
1
>>> -8 % -3
-2
For an explanation of why it was implemented this way, read the blog post by Guido.
integer math is funny:
>>> -8//3 # (-8/3 in python2 does the same thing)
-3
>>> 8//3 # (8/3 in python2 does the same thing)
2
>>>
Rounding is done down, not towards zero.
3%3 = 0
2%3 = 2
1%3 = 1
0%3 = 0
-1%3 = 2
-2%3 = 1
-3%3 = 0
...
-7%3 = 2
-8%3 = 1
Be careful: (-8)%3 != -(8%3)
Let's look at (one common interpretation of) integer division:
Given a, b, d, r in N
and b > 0
and 0 <= r < b
, then:
a // b = d
and a % b = r
iff
a = d * b + r
.
Hence: From -8 = -3 * 3 + 1
and -8 // 3 = -3
follows -8 % 3 = 1
>>> -8 == -3 * 3 + 1
True
>>> -8 // 3
-3
>>> -8 % 3
1
>>> (-8 // 3) * 3 + (-8 % 3) == -8
True
-8 = -3*3 + 1
In math the rest is ALWAYS positive so that in a = m*k + r k is integer and r is integer but with 0 <= r < |m|