simple math question

Dave Hansen iddw at hotmail.com
Mon Feb 13 15:51:56 EST 2006


On Sat, 11 Feb 2006 16:43:33 -0500 in comp.lang.python, John Salerno
<johnjsal at NOSPAMgmail.com> wrote:

>John Salerno wrote:
>> Hi all. I'm just starting out with Python, so I'm a little slow right 
>> now. :)
>> 
>> Can someone explain to me why the expression 5 / -2 evaluates to -3, 
>> especially considering that -2 * -3 evaluates to 6?
>> 
>> I'm sure it has something to do with the negative number and the current 
>> way that the / operator is implemented, but why doesn't it evaluate to 
>> -2 instead?
>
>Thanks for the help guys! It's clearer to me now, and I think I was just 
>conceptualizing it the wrong way in the first place.

Probably not the "wrong" way, just a different way, especially if you
write C code.  

The C standard defines integer division as (something like) "the
integer part of the result, throwing away the fraction," which would
get you the value you expect.  

This also means the sign of the result of the C % operator matches the
sign of the numerator.  In Python, the sign matches the sign of the
denominator.

You could also describe the C scheme as "truncating towards zero."
Python (and my HP calculator) "truncates toward negative infinity."  I
suppose a third way to do it would be to "truncate towards positive
infinity," but I don't know of any concrete examples of this.  'Twould
seem counter-intuitive in any case...

Regards,
                                        -=Dave

-- 
Change is inevitable, progress is not.



More information about the Python-list mailing list