4

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Java Guy
  • 83
  • 3

5 Answers5

10

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.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    From the docs "The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand". This agrees with that as well. – SethMMorton Jan 21 '14 at 19:18
5

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.

mhlester
  • 22,781
  • 10
  • 52
  • 75
1
 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)

WebF0x
  • 165
  • 9
1

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
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87
0

-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|

Alvaro Fuentes
  • 16,937
  • 4
  • 56
  • 68