simple math question

Dan Bishop danb_83 at yahoo.com
Sat Feb 11 17:21:24 EST 2006


Paul Rubin wrote:
> 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).

As a more concrete example, consider the case of a Date class that
stores dates as the number of days since an epoch, which happens to be
a Sunday.  To compute the day of the week a date falls on, you could
use:

SUNDAY, MONDAY, ..., SATURDAY = xrange(7)

class Date:
   ...
   def weekday(self):
      return self.daycount % 7


But what about the day BEFORE the epoch, represented by -1?

Case 1: Suppose that -1 // 7 == 0, as it is in C.  In order to preserve
that

> You want (b*(a/b) + a%b)==a at all times.

With a=-1, b=7, and a//b=0, this means (7*0 + a%b)==-1, which requires
that -1 % 7 == -1.  This doesn't correspond to any of the weekday
constants, which means you'd have to rewrite your weekday() method if
you wanted to handle negative dates.

Case 2: Suppose that -1 // 7 = -1.

Then (7*(-1) + -1%7)==-1, which means -1%7 happens to be 6.  This says
that the day before the epoch is a Saturday, which is exactly what you
want.

> Since a%b is positive, you can use it as a list index, etc.

This isn't the best explanation, because negative list indices *are*
allowed.




More information about the Python-list mailing list