negative integer division

Robert Kern rkern at ucsd.edu
Mon Feb 7 19:30:48 EST 2005


Imbaud Pierre wrote:
> integer division and modulo gives different results in c and python, 
> when negative numbers
> are involved. take gdb as a widely available c interpreter
>  print -2 /3
> 0 for c, -1 for python.
> more amazing, modulos of negative number give negative values! (in c).
> from an algebraic point of view, python seems right, but I thought 
> python conformity to the underlying c compiler was a strong commitment, 
> obviously not here, and I found no explanation whatsoever in python doc.
> no actual programming challenge for me here, I just had this bug, after 
> confidently translating from python to c.

I don't think there's much *commitment* to follow the behaviour of your 
C compiler. It's more of a default stance when the issues get too 
complicated for Python to implement itself. Thus, much of the floating 
point behaviour defaults to the behaviour of your platform because 
floating point math is hard and getting consistent behaviour on lots of 
platforms is really hard.

Integers are a piece of cake, relatively speaking, and I think that it's 
worth fixing up a few warts from the C behaviour.

As for documentation, see 
http://www.python.org/doc/current/lib/typesnumeric.html

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter



More information about the Python-list mailing list