Integer division & modulo operation with negative operands in Python

后端 未结 4 557
时光说笑
时光说笑 2020-11-27 07:13

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

4条回答
  •  执笔经年
    2020-11-27 07:49

    • Magic formula: a = (a // b) * b + (a % b)
    • a: -10
    • b: 3
    • a // b: -4
    • a % b: 2

      Substitute in magic formula: -10 = -4 * 3 + 2 = -12 + 2 = -10

    • a: 10

    • b: -3
    • a // b: -4
    • a % b: -2

      In magic formula: 10 = -4 * -3 - 2 = 12 - 2 = 10

    So the magic formula seems to be correct.

    If you define a // b as floor(a / b) (which it is), a % b should be a - floor(a / b) * b. Let's see:

    • a: -10
    • b: 3
    • a % b = a - floor(a / b) * b = -10 - floor(-3.33) * 3 = -10 + 4 * 3 = 2

     

    The fact that a // b is always floored is pretty easy to remember (please read Cthulhu's first link, it's an explanation by the creator of Python). For negative a in a % b.. try to imagine a table of numbers that starts at 0 and has b columns:

    b = 3:
    
    0  1  2
    3  4  5
    6  7  8
    9 10 11
    ...
    

    If a is the number in a cell, a % b would be the column number:

    a         a % b
    _______________
    0  1  2   0 1 2
    3  4  5   0 1 2
    6  7  8   0 1 2
    9 10 11   0 1 2
    

    Now extend the table back in the negatives:

       a          a % b
     __________________
    -12 -11 -10   0 1 2
     -9  -8  -7   0 1 2
     -6  -5  -4   0 1 2
     -3  -2  -1   0 1 2
      0   1   2   0 1 2
      3   4   5   0 1 2
      6   7   8   0 1 2
      9  10  11   0 1 2
    

    -10 % 3 would be 2. Negative a in a % b would come up in these sorts of context. a % b with negative b doesn't come up much.

提交回复
热议问题