1/2 evaluates to 0

Chris Angelico rosuav at gmail.com
Wed Oct 12 06:29:58 EDT 2011


On Wed, Oct 12, 2011 at 9:14 PM, Laurent Claessens <moky.math at gmail.com> wrote:
> Hi all
>
> This is well known :
>
>>>> 1/2
> 0

Only in Python 2.

> This is because the division is an "integer division".
>
> My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer
> division operator ?

1.0/2 is floating point division, but you can also use:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0

This is the most portable option. Stick with // for integer division
and tell / to produce a float (which it will do even if the result
would have fitted into an integer).

Note that the __future__ directive needs to be at the top of your program.

ChrisA



More information about the Python-list mailing list