Modulo operator : differences between C and Python

John Machin sjmachin at lexicon.net
Mon Mar 11 01:00:02 EST 2002


Erik de Castro Lopo <nospam at mega-nerd.com> wrote in message news:<3C8BE537.74E55963 at mega-nerd.com>...
> Hi all,
> 
> 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.
[snip]
> Anybody have any idea why this is?

The Python reference manual: "The modulo operator always yields a
result with the same sign as its second operand (or zero)"

K&R2, p. 205 says: [paraphrased] If both operands are non-negative,
then the remainder is non-negative and smaller than the divisor; if
not, it is guaranteed only that abs(remainder) < abs(divisor).

So what you see from C depends on the compiler and architecture. If
you are at all interested in portablity of your C code, you will need
to take precautions.

Why? Philosophy, I suppose: C gives you generally what the hardware
gives you. Python mostly gives you what is useful and consistent, even
if the implementation has to work a bit harder to do that.

There is also a lengthy thread in this newsgroup -- you can easily
find it by googling "modulo remainder negative".

<:-)>
BTW, speaking of "easily find", were you having simultaneous problems
with all of (1) the index in K&R (2) the Python reference manual (3)
Google???
</:-)>



More information about the Python-list mailing list