-1/2

Duncan Booth duncan.booth at invalid.invalid
Mon Jun 23 17:00:07 CEST 2008


Lie <Lie.1296 at gmail.com> wrote:

> On Jun 23, 1:32 am, "Serve Lau" <ni... at qinqin.com> wrote:
>> What is the expected result of -1/2 in python?
> 
> 
> Operator precedence:
> Both python 2 and 3 follows the same rule for operator precedence,
> see:
> http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.htm
> l . In -1/2, unary negative takes precedence, then division, i.e. it's
> interpreted as ((-1) / 2).
> 
> Py3k and Python 2 differences:
> Before Python 3, integer division is always rounds to minus infinity.
> In Python 3, integer division yields floats. To use integer division
> in Python 3, you use // operator.
> 
> Simple answer:
> Python 2: (-1)/2 = round(-0.5)          = -1
> Py3k:     (-1)/2 = float(-1) / float(2) = -0.5
> 
Python 2.x gives -1 or -0.5 depending on the division mode in operation and 
for -1 may also generate a deprecation warning:


C:\>python25\python -Qnew -c "print -1/2"
-0.5

C:\>python25\python -Qwarn -c "print -1/2"
-c:1: DeprecationWarning: classic int division
-1


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list