simple math question
Paul Rubin
http
Sat Feb 11 15:38:13 EST 2006
John Salerno <johnjsal at NOSPAMgmail.com> writes:
> 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?
Well, -2 * -2 is 4, which is not especially better than 6. The
reason for choosing -3 instead of -2 is so that if b is positive,
then a%b is non-negative even if a is negative. That is, the
motivating case is (-5 % 2) which is done the same way as (5 % -2).
You want (b*(a/b) + a%b)==a at all times. If (-5 / 2) = -3, then you
need (-5 % 2) = -1. But if (-5 / 2) = -2, then (-5 % 2) = +1.
Since a%b is positive, you can use it as a list index, etc.
More information about the Python-list
mailing list