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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With