[omaha] Tutorial: integer division

Jeff Hinrichs - DM&T jeffh at dundeemt.com
Sat Dec 1 17:27:20 CET 2007


You are correct that it is a problem and one that is going to be
changed in the future.  Currently 2.5.x and previous all division
defaulted to integer division, you had to make at least one number a
floating point.   You can change the current behavior and jump in to
the future by using the __future__ module (not kidding) .  Here is an
example:

jlh at jlh-d520:~$ python
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/3
0
>>> 2/3.0
0.66666666666666663
>>> from __future__ import division
>>> 2/3
0.66666666666666663
>>> 2//3
0
>>>

You will notice that the division from __future__ defaults to the more
commonly used definition of '/'  and if you want the old style integer
division you would use //

The __future__ module (note the double underscores on both sides)
contains those approved and upcoming changes.  It provides a way to
test current code against upcoming changes and take advantage of new
features before they are made part of the core.  see

>>> import __future__
>>> help(__future__)

for more details

-jeff

On Dec 1, 2007 8:26 AM, Jay Hannah <jay at jays.net> wrote:
> This surprised me:
>
> http://docs.python.org/tut/node5.html
>
>  >>> # Integer division returns the floor:
> ... 7/3
> 2
>
> So I tried my own:
>
>  >>> x = 7
>  >>> y = 3
>  >>> x / y
> 2
>
> This strikes me as very counter-intuitive... How do you avoid getting
> burned by this?
>
> Forcing a decimal point into the mix does what I expect:
>
>  >>> x = 7.0
>  >>> y = 3
>  >>> x / y
> 2.3333333333333335
>
> But how do I systematically enforce floating point division into my
> applications?
>
> Thanks,
>
> j
> didn't even mention Perl. Aren't you proud of me? -grin-
>
> _______________________________________________
> Omaha Python Users Group mailing list
> Omaha at python.org
> http://mail.python.org/mailman/listinfo/omaha
> http://www.OmahaPython.org
>



-- 
Jeff Hinrichs
Dundee Media & Technology, Inc
jeffh at dundeemt.com
402.218.1473


More information about the Omaha mailing list