Modulo operator : differences between C and Python

Tim Peters tim.one at comcast.net
Sun Mar 10 18:37:37 EST 2002


[Erik de Castro Lopo]
> Just recently I prototyped a relatively complex algorithm in Python
> before converting it to C. During this conversion I noticed that
> the modulo operator returns different results in C and Python if
> the numerator is negative. For positive values they produce the same
> result.

Python defines the result of i%j to have the same sign as j; what C requires
depends on which year's C standard you're looking at (it was left up to
implementers' discretion before the 1999 standard); the C implementations I
use return a result with i's sign, and I usually curse them for that.

Note that this is related to what "i/j" returns.  Both languages preserve

    i == (i/j)*j + i%j

in non-pathological cases (j != 0, etc).





More information about the Python-list mailing list