How python calculate this modulo? -
how python calculate mathematically modulo?
>>>-1%10 9
the wikipedia article on modulo operation provides following constraint a % q:
a = nq + r substituting a = -1, q = 10 , r = 9, see n must equal -1.
plugging in -1 n:
-1 % 10 # python evaluates 9 -1 = n * 10 + r -1 = -1 * 10 + r 9 = r testing example (again plugging in -1 n):
-7 % 17 # python evaluates 10 -7 = n * 17 + r -7 = -17 + r 10 = r a third example positive numerator , negative denominator:
7 % -17 # python evaluates -10 7 = n * (-17) + r 7 = -1 * (-17) + r 7 = 17 + r -10 = r it appears when a , q have different signs, start n = -1 , decrement n 1 until we've found n closest 0 such n*q < a. can test trying out a , q such |a| > |q|:
-100 % 11 # python evaluates 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 might not algorithm python uses calculate modulo, @ least have useful mental model reasoning how given result arrived at.
Comments
Post a Comment