Version compatibility in division

David Bolen db3l at fitlinxx.com
Wed Jul 25 22:37:26 CEST 2001


Duncan Grisby <dgrisby at uk.research.att.com> writes:

> In article <loj77.544242$eK2.114179510 at news4.rdc1.on.home.com>,
>  Nick Perkins <nperkins7 at home.com> wrote:
> 
> >I suppose the only cross-version solution would be:
> >
> >     # Script MUST run under various Python versions without change
> >     ...
> >     print int(container/widget) ,'widgets will fit in the container'
> >
> >It's a tiny bit verbose, but at least it's very explicit.
> 
> And also wrong in the face of negative divisors (although you probably
> wouldn't have a negative number of widgets :-) ).
> 
>   >>> 5/-2
>   -3
>   >>> int(5.0/-2.0)
>   -2
> 
> The "simple" solution is divmod(container, widget)[0]. Lovely.

Simple if you need to ensure negative number behavior.  I'd hazard a
guess that of all the existing code that depends on integer division,
a majority will never have a negative number.  So for that portion,
(or for that portion of future code for which its known the integer
division is on positive values), int(expr) might well be the simplest
approach.

Then again, the bigger problem with int() is the potential for
rounding that is, at least theoretically, permitted by the
implementation, although as someone else pointed out, it's not clear
that any C libraries actually do that.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list