Why python incorrectly divides with remainder?

42% 10 = 2
That is correct, but
-42 % 10 = 8
Why?
March 23rd 20 at 19:00
2 answers
March 23rd 20 at 19:02
Solution
Because just the same from a mathematical point of view, Python unlike Serznyh languages, it is doing the right thing.
-42 // 10 = -5
-42 % 10 = 8
---------------
-5 * 10 + 8 = -42


UP: Well, since such issues, it is necessary to read the modulo operator, and tenderloin out:
Division with a remainder ("the dividend") to b (the divisor) means finding integers q and r that the validity of the equation:
a=b*q+r
March 23rd 20 at 19:04
Solution
The fact that when dividing with a remainder, the remainder must be positive. This means that when dividing with a remainder of negative numbers, we need a positive balance to find from a SMALLER number. It turns out that when dividing with remainder 42 10 we reject less delimuyu a part: 40. Remains 2. So by dividing -42 with the remainder we discard less delimuyu a part of: -50, leaving a positive balance equal to -42: -50 - (-42) = -50 + 42 = 8.

Find more questions by tags Python