Question about Py 2.2.x division operator

John Roth johnroth at ameritech.net
Sun Dec 29 15:52:12 EST 2002


"ahimsa" <ahimsa at onetel.net.uk> wrote in message
news:mailman.1041190641.1399.python-list at python.org...
> I am using Python 2.2c1 and have a query regarding the use of division
> operators.
> I haven't seen this covered previously, but if it has, my apologies
for
> redundancy.
> I understand that pre-2.2 the '/' would only perform 'floor' division
> and truncate the remainder -- e.g. 7 / 4 == 1 -- but that with 2.2
'//'
> would be used for floor division and '/' would be used for true
division
> -- e.g. 7 // 4 == 1 while 7 / 4 == 1.75. When I try this I can get the
> fraction by using real numbers (i.e. 7.0 / 4 == 1.75) *without*
> importing the future module, so what are the advantages of importing
the
> division component of the 'future' module unless I was only going to
be
> using integers? Would it be a useful 'failsafe' to reduce errors?

Neither one. Division ('/') has always worked that way, that is, if
one of the operands is a float, then the result is a float. It will
continue to work that way in the future. The "problem" was that
if both operands were integers, then the result would be an
integer, which means that the result would be truncated to what
could be represented by an integer.

The changes in 2.2 are twofold:

1. The new // operator which *always* performs floor
division regardless of the type of its operands or result,

and

2. the future division module, which forces the '/' operator to
always return a float with the real result, regardless of the
types of its operands. For compatibility, you will need to import
this until the mythical Python 3.0 release.

Whether this means anything at all to your programs depends
on your applications. AFIC, there's no good solution other than
to be consistent about each and every use of the division ('/')
operator as to whether it's using floats or integers, and whether
you want an integer, truncated float or full precision float result.

John Roth
>
> Cheers
> AmF
>
> --
> ahimsa <ahimsa at onetel.net.uk>
>
>





More information about the Python-list mailing list