[Python-ideas] division oddness

Brett Cannon brett at python.org
Fri May 7 20:46:39 CEST 2010


On Thu, May 6, 2010 at 17:43, Mathias Panzenböck <
grosser.meister.morti at gmx.net> wrote:

> Shouldn't by by mathematical definition -x // y be the same as -(x // y)?
> But when assign x=2, y=3 you get:
>
> >>> -2 // 3
> -1
> >>> -(2 // 3)
> 0
>
> And also:
> >>> 2 // -3
> -1
> >>> -2 // -3
> 0
>
> And even more:
> >>> int(-2 / 3)
> 0
> >>> int(2 / -3)
> 0
>
> I think this rather odd. Is there any deeper reason to this behaviour? I
> guess changing this will break a lot of code, but why does it behave like
> this?
>

Operator precedence; unary negation (the 'factor' rule from Grammar/Grammar)
binds more tightly than // (the 'term' rule), thus applying the negation to
'2' before applying the '//'. Making it bind as `-(x // y)` would require
introducing a special grammar rule just to make sure that unary negation on
binary operators like this worked this way. And I am not even sure if that
would be unambiguous in Python's LL(1) grammar.

-Brett


>
>        -panzi
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20100507/38778903/attachment.html>


More information about the Python-ideas mailing list