Search code examples
pythonmodulointeger-divisionnegative-numberoperand

Integer division & modulo operation with negative operands in Python


Questions arise when I type in these expressions to Python 3.3.0

-10 // 3  # -4
-10 % 3   #  2
10 // -3  # -4
10 % -3   # -2
-10 // -3 #  3

It appears as though it takes the approximate floating point (-3.33)? and rounds down either way in integer division but in the modulo operation it does something totally different. It seems like it returns the remainder +/-1 and only switches the sign depending on where the negative operand is. I am utterly confused, even after looking over other answers on this site! I hope someone can clearly explain this too me! The book says hint: recall this magic formula a = (a//b)(b)+(a%b) but that doesn't seem to clear the water for me at all.

-Thanks in advance!

Edit: Those are just my personal assessments of what happens (above), I know, I'm completely off!


Solution

  • The integer division there is just taking the floor of the number obtained at the end.

    10/3  -> floor(3.33)  ->  3
    -10/3 -> floor(-3.33) -> -4
    

    (Why it floors)


    The modulo operation on the other hand is following the mathematical definition.