Question about Py 2.2.x division operator
Dan Bishop
danb_83 at yahoo.com
Sun Dec 29 19:49:16 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,
As it should. For floats, the / operator has always used true
division.
This means the value of x/y depends on the types of x and y. This is
also the case in C and Java, but it's less of a problem in those
languages.
> so what are the advantages of importing the
> division component of the 'future' module unless I was only going to be
> using integers?
The problem is that you can't always be sure of what type you're
using. For example, suppose that one of the operands of your / was a
number input by the user. Your function might expect a float, but one
of these days you'll type a whole number, forget to put a decimal
point after it, and wonder why your program is giving strange answers.
In C, it wouldn't matter, because when you write something like
double mid(double x, double y) {
return (x + y) / 2;
}
...
mid(anInt, anotherInt);
the compiler will add code to convert mid's arguments to
floating-point values, and you'll get the true division you'll expect.
Not so in Python: mid(3, 4) != mid(3., 4.).
To guarantee consistent results in Python, you can add explicit
floatifying:
def mid(x, y):
return (x + y) / 2.
def mid(x, y):
return float(x + y) / 2
But there's the possibility that you'd forget to, or that you'd get
annoyed by having to type "float" everywhere and wish this behavior
was the default. That's where "from __future__ import division" comes
in.
More information about the Python-list
mailing list