Modulo operator : differences between C and Python
Erik de Castro Lopo
nospam at mega-nerd.com
Sun Mar 10 17:59:03 EST 2002
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.
----------------------------------------------------------------
erikd at coltrane > python
Python 2.1.2 (#1, Jan 18 2002, 18:05:45)
[GCC 2.95.4 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> 123 % 12
3
>>> -123 % 12
9
>>>
erikd at coltrane > cat mod_test.c
#include <stdio.h>
int main (void)
{ int a = 123 ;
printf (" % d %% 12 == %d\n", a, a % 12) ;
printf (" % d %% 12 == %d\n", -a, -a % 12) ;
return 0 ;
}
erikd at coltrane > gcc -Wall mod_test.c -o mod_test
erikd at coltrane > ./mod_test
123 % 12 == 3
-123 % 12 == -3
----------------------------------------------------------------
Anybody have any idea why this is?
Erik
--
+-----------------------------------------------------------+
Erik de Castro Lopo nospam at mega-nerd.com (Yes it's valid)
+-----------------------------------------------------------+
The government everybody loves to abuse sues the company everybody loves
to hate. Throw in a bunch of faceless lawyers cross-examining techies
[with] all the charisma of a video driver and you've got a spectacle of
thoroughly miniscule proportions.
More information about the Python-list
mailing list