2

When a-b*i becomes negative, why is -8 % 5 2, rather than 3 or -3, when using Python 2.7.

a = 12
b = 5

for i in range(10):
    print a-b*i, (a-b*i) % b

12 2
7 2
2 2
-3 2
-8 2
-13 2
-18 2
-23 2
-28 2
-33 2
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Lin Ma
  • 9,739
  • 32
  • 105
  • 175
  • 1
    Note: it could not be 3, because -8 ≢ 3 (mod 5) – spectras Mar 07 '16 at 20:30
  • @spectras, thanks for the response and vote up. I am thinking like this, why not -8 = 5 * -1 + (-3)? And this is where my confusion comes from. Though result could be -3. :) Your advice is appreciated. – Lin Ma Mar 07 '16 at 22:08
  • 1
    Result could be either -3 or +2, indeed. Python chooses the result that has the sign of the right-hand operand while some other languages choose the result that has the sign of the left-hand operand. – spectras Mar 08 '16 at 12:03

1 Answers1

1

You can check it yourself using google calculator:

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=-8+%25+5

when you do Euclidian divison of a/n, you get a reminder. The whole deal should satisfy an equation a = qn + r where q is a quotient, that belongs to Z ( integers from -inf to +inf) So in your case

-8 = 5 * (-2) + 2
thus 
r = 2 = (-8) % 5
Stanley Kirdey
  • 602
  • 5
  • 20
  • Thanks Stanley, but why not `-8 = 5 * -1 + (-3)`? And this is where my confusion comes from. Though result could be -3. :) – Lin Ma Mar 07 '16 at 22:07
  • Hi Stanley, do you miss a link? :) – Lin Ma Mar 07 '16 at 23:38
  • 1
    yep: -) from the Python docs: The modulo operator always yields a result with the same sign as its second operand (or zero); In your example remainder would be (-3), which is negative. Also, Python enforces tis properties, abs(a%b) < abs(b) and, 0 <= r < b. – Stanley Kirdey Mar 08 '16 at 00:02
  • 1
    I believe you are getting the 2 because Python floors the quotient to negative infinity. Here are some examples: `# Per http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html` `# Python floors quotient to negative infinity` `import math` `print (8 / 5) # Outputs: 1` `print (-8 / 5) # Outputs: -2` `print (-8.0 / 5.0) # Outputs: -1.6` `print(math.floor(-8.0 / 5.0)) # Outputs: -2` `print ( -8 % 5 ) # Outputs 2` – Stanley Kirdey Mar 08 '16 at 00:09
  • Thanks Stanley, vote up! :) For your comments "result with the same sign as its second operand (or zero)", in my sample, -8 % 5, the 2nd operand is 5? Correct? Thanks. – Lin Ma Mar 08 '16 at 01:26
  • BTW, in my sample, -8 % 5, what is the negative infinity? – Lin Ma Mar 08 '16 at 04:30