23 % -5 = -2
23 % 5 = 3
Can someone explain to me how I can understand this because I have an exam tomorrow. I want to say its because -5 * -5 =25
then 25 -2 = 23
which is how they get the 23
. Is this correct?
23 % -5 = -2
23 % 5 = 3
Can someone explain to me how I can understand this because I have an exam tomorrow. I want to say its because -5 * -5 =25
then 25 -2 = 23
which is how they get the 23
. Is this correct?
In Python, the sign of the remainder is the same as the sign of the denominator (which differs from languages like C, where it is the same as the sign of the numerator).
Mathematically, you are always guaranteed that if a, b = divmod(n, d)
, then a*d + b == n
.
Note that 23//5 == 4
and 23//-5 == -5
(Python always does floor division). Thus, we have 4*5 + 3 == 23
and -5*-5 - 2 == 23
, as you have said.
The simplest way of looking at problem for your purposes is to consider the definition that:
a mod n = R where the remainder R must satisfy 0<= R
So for mod -5 arithmetic, 0<= R < -4 i.e. R can be one of 0, -1, -2, -3, -4
that is you effectively subtract (or add) n from a until you bring R into the range above:
So
23 % 5 is (23-4*5) = 23-20 = 3
but
23 % -5 is (23+5*(-5)) = 23-25 = -2
Well, 23 % 5 = 3 since 4*5 = 20 and when you divide 23 by 20 you obtain a remainder of 3. You can think of it as the closet you can go without going over.
As for 23 % -5, well that answer differs from one programming language to another.
For Python it's -2 because it will always return the value of the divisor and it's because 5*5 = 25 and when you divide 23 by 25 in Python you obtain a remainder of -2 (since it must be negative because the divisor was negative) so we have 25 - 2 = 23.
It's worth noting that the formal mathematical definition states that b is a positive integer.
% in Python uses "Modulo operation" ; it's different from taking the reminder of a division operation such that.
a - int(a/n) * n
although it is sometimes equivalent in some computer languages.
The math expression can be found explict here: http://en.wikipedia.org/wiki/Modulo_operation
So obviously, in Python "%" operation uses the following expression:
mod(a, n) = a - n * floor(a / n)
Therefore,
23%-5 = mod(23,-5) = 23 - (-5) * floor(23/-5) = 23 - (-5) * -5 = -2
and
23%5 = mod(23, 5) = 23 - 5 * floor(23/5) = 23 - 5 * 4 = 3
In addition, you my find it's interesting that
-23%5 = mod(-23,5) = (-23) - 5 * floor(-23/5) = -23 - 5 * (-5) = 2
since floor() action will take the integer value toward negative infinity.