inicio mail me! sindicaci;ón

mod is not mod

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) :-P ) 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.7 equals 0.34 (since 3.14 equals 4*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.

Related posts

  • Django, image uploading, validation and newforms
  • Qualità dei tutorial Python
  • Gravatar

    Andrew Dalke said,

    June 2, 2006 @ 5:08 pm

    ANSI C says that the result of modulus with a negative number is implementation-defined, meaning it must be reasonable and documented. A C compiler could return either positive or negative. Python’s % operator on numbers agrees with ANSI C. However, just about all C compilers return a negative number for this case.

    RSS feed for comments on this post