negative numbers modulo in python -
i've found strange behaviour in python regarding negative numbers:
>>> = -5 >>> % 4 3
could explain what's going on?
unlike c or c++, python's modulo operator (%
) return number having same sign denominator (divisor). expression yields 3 because
(-5) % 4 = (-2 × 4 + 3) % 4 = 3.
it chosen on c behavior because nonnegative result more useful. example compute week days. if today tuesday (day #2), week day n days before? in python can compute with
return (2 - n) % 7
but in c, if n ≥ 3, negative number invalid number, , need manually fix adding 7:
int result = (2 - n) % 7; return result < 0 ? result + 7 : result;
(see http://en.wikipedia.org/wiki/modulo_operator how sign of result determined different languages.)
Comments
Post a Comment