negative integer division

Scott David Daniels Scott.Daniels at Acm.Org
Mon Feb 7 19:33:20 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.
> 
If you read the C standard, you can see that the C compiler is free to
make -1 / 3 either -1 or 0 (but it must describe what it does).  The
decision is usually to do whatever the underlying CPU does.  The
rationale is that often you will be dividing positive by positive,
and you don't want the compiler sprinkling around a lot of test code.

While the difference in compiled C is a substantial time penalty
(DIVIDE vs. DIVIDE; COMPARE; JUMPGE), in Python the trade-off is
adding two instructions to many (50? 100?).  Python doesn't really
mind paying for a few extra instructions to get the canonical value,
and the guarantee simplifies the user's code.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list