Modul (%) in python not like in C?

Scott David Daniels Scott.Daniels at Acm.Org
Mon Sep 10 23:36:05 EDT 2007


Bryan Olson wrote:
> Dotan Cohen wrote:
...
>> Second, in Turbo C -111%10=-1 however in python -111%10=9. Is one or
>> the other in error? 
> 
> Turbo C is correct here with respect to the C standard. Python
> is correct with respect to the Python Reference Manual.
> 
> They also disagree about integer division. C rounds toward zero;
> Python rounds downward.
> 
> In C:       -111 / 10  evaluates to -11
> In Python:  -111 / 10  evaluates to -12

C, which was designed as a "high level assembly language," does not
tightly define the results of / and % for negative numbers.  Instead
it defines the result for positive over positive, and constrains the
result for the others.  The reason is simple: most CPUs available
at the time provided a single operation that produced both the quotient
and the remainder, but some produced -1 for -3 / 2, and others produced
1 for -3 / 2.  Either result is justifiable, but the most common use
of division and remainder is positive / positive, and it would be a
shame to generate a test for every division and modulus just to cover
the negative / positive case.  You would be slowing down the majority
of code to satisfy the (usually non-existant) corner case.

-Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list