Yesterday when I was testing the wrapped time module I noticed a test failing on and on without any particular reason. So I dug in (with print(s)
) and found out an interesting thing in which Python implementation differs from ANSI C’s
the mod (% and also operator.mod in Python) operator have a different behaviour in the two platforms. Here’s an example:
[code lang="c"] int i = -2; printf(”%d\n”, (i + 1) % 7); [/code]
This will print -1
[code lang="python"] i = -2 print (i + 1) % 7 [/code]
This will print 6 The reason is explained in the Python Language Reference: http://docs.python.org/ref/binary.html
The%(modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g.,3.14%0.7equals0.34(since3.14equals4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand
ANSI C doesn’t have the restriction in bold. So I made the failing test pass using math.fmod() which resemble the ANSI C behavior.
