How python calculate this modulo?
python如何以数学方式计算这个模数?
>>>-1%10
9
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.
Its is caluclated like this :-
-10 / 10 = -1
,
hence remainder 9
.
-10
is greatest multiple of 10
which is less than -1
.
It is similar to 9 % 5
, will be greatest number less than dividend should be considers.
5/5 = 1
, hence 4
.
I'm not sure if you're asking the algorithm that python uses, or why the answer comes out this way.
If the latter, imagine that for modulo n
you subtract or add n
until you get a number between 0
and n-1
inclusive
上一篇: 可理解的模数计算
下一篇: python如何计算这个模数?