Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "**" bind more tightly than negation?

I was just bitten by the following scenario:

>>> -1 ** 2
-1

Now, digging through the Python docs, it's clear that this is intended behavior, but why? I don't work with any other languages with power as a builtin operator, but not having unary negation bind as tightly as possible seems dangerously counter-intuitive to me.

Is there a reason it was done this way? Do other languages with power operators behave similarly?

like image 753
Ben Blank Avatar asked Jun 01 '09 21:06

Ben Blank


1 Answers

Short answer: it's the standard way precedence works in math.

Let's say I want to evaluate the polynomial 3x3 - x2 + 5.

def polynomial(x):
    return 3*x**3 - x**2 + 5

It looks better than...

def polynomial
    return 3*x**3 - (x**2) + 5

And the first way is the way mathematicians do it. Other languages with exponentiation work the same way. Note that the negation operator also binds more loosely than multiplication, so

-x*y === -(x*y)

Which is also the way they do it in math.

like image 54
Dietrich Epp Avatar answered Sep 30 '22 12:09

Dietrich Epp