Integer math question

Dan Bishop danb_83 at yahoo.com
Sun Jan 4 19:59:35 EST 2004


mersmann at szut.uni-bremen.de (Frank) wrote in message news:<3987e01c.0401030832.114c6f2a at posting.google.com>...
> Hi,
> 
> can anybody help with the following problem?
...
> i = 5 / 10 	gives me 0 as expected, but
> i = -5 / 10 	gives -1 as result.

The problem is that you aren't using "from __future__ import division"
;-)  (This causes the results to be 0.5 and -0.5, and will be the
default division semantics in Python 3.0.  If you want integer
division, use the // operator.)

> Is this a feature or a bug?

It's a feature.  The advantage of defining x // y as floor(x / y) is
that x % y is always nonnegative.

As as example of why this is useful, consider the
datetime.date.weekday method.  This could be implemented as

   def weekday(self):
      return (self.fromordinal() - 1) % 7

If the datetime module was changed to allow BC(E) dates (which have
nonpositive Rata Die numbers), the weekday method would still work. 
In C++, you'd have to treat such dates as a special case.



More information about the Python-list mailing list