Search code examples
pythonmodulonegative-number

How python calculate this modulo?


How python calculate mathematically this modulo?

>>>-1%10  
9

Solution

  • The Wikipedia article on the modulo operation provides the following constraint for a % q:

    a = nq + r
    

    Substituting a = -1, q = 10 and r = 9, we see that n must be equal -1.

    Plugging in -1 for n:

    -1 % 10  # Python evaluates this as 9
    -1 = n * 10 + r
    -1 = -1 * 10 + r
    9 = r
    

    Testing with another example (again plugging in -1 for n):

    -7 % 17  # Python evaluates this as 10
    -7 = n * 17 + r
    -7 = -17 + r
    10 = r
    

    A third example with a positive numerator and negative denominator:

    7 % -17  # Python evaluates this as -10
    7 = n * (-17) + r
    7 = -1 * (-17) + r
    7 = 17 + r
    -10 = r
    

    It appears that when a and q have different signs, we start with n = -1 and decrement n by 1 until we've found the n closest to zero such that n*q < a. We can test this by trying this out with an a and q such that |a| > |q|:

    -100 % 11  # Python evaluates as 10
    -100 = n * 11 + r
     ...   -1  # -11 > -100
     ...   -2  # -22 > -100
     ...   -3  ...
     ...   -4  ...
     ...   -5  ...
     ...   -6  ...
     ...   -7  ...
     ...   -8  ...
     ...   -9  # -99 > -100
     -100 = -10 * 11 + r  # -110 < -100
     -100 = -110 + r
     10 = r
    

    So while this might not be the algorithm Python actually uses to calculate the modulo, we at least have a useful mental model for reasoning about how a given result was arrived at.