3 ms·
That is actually an error in the python implementation. According to the language reference: "(a/b)*b + (a%b) = a" where the (a/b) step is rounded towards 0. Th
by newt0311 19y ago
That is actually an error in the python implementation. According to the language reference: "(a/b)*b + (a%b) = a" where the (a/b) step is rounded towards 0. This implies the if a is negative, (a%b) should also be negative. Note that this modulus standard is also used for the C, C++, and JAVA standard. Here, its python's mess up.
- bayareaguy 19y agoThis implies the if a is negative, (a%b) should also be negative. No, python is giving you the Modulus after division (i.e. a "distance" which should be positive). If you interpret it that way everything is fine: >>> a = -1 >>> b = 3 >>> (a/b)*b -3 >>> (a%b) 2 >>> (a/b)*b + (a%b) -1 Perhaps you're thinking of the Remainder? Edit: it seems there isn't much consensus about what to do when a or b are negative. Wikipedia gives a helpful chart here how different languages choose to implement this: http://en.wikipedia.org/wiki/Modulo_operation http://en.wikipedia.org/wiki/Modulo_operation
- newt0311 19y agoTrue. I checked the python reference again and it re-adjusts the modulo to have the same sign as the 2nd operand. >>> 1 % -3 -2 >>> -1 % -3 -1