Question

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?

Was it helpful?

Solution

That behaviour is the same as in math formulas, so I am not sure what the problem is, or why it is counter-intuitive. Can you explain where have you seen something different? "**" always bind more than "-": -x^2 is not the same as (-x)^2

Just use (-1) ** 2, exactly as you'd do in math.

OTHER TIPS

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 I had to guess, it would be because having an exponentiation operator allows programmers to easily raise numbers to fractional powers. Negative numbers raised to fractional powers end up with an imaginary component (usually), so that can be avoided by binding ** more tightly than unary -. Most languages don't like imaginary numbers.

Ultimately, of course, it's just a convention - and to make your code readable by yourself and others down the line, you'll probably want to explicitly group your (-1) so no one else gets caught by the same trap :) Good luck!

It seems intuitive to me.

Fist, because it's consistent with mathematical notaiton: -2^2 = -4.

Second, the operator ** was widely introduced by FORTRAN long time ago. In FORTRAN, -2**2 is -4, as well.

Ocaml doesn't do the same

# -12.0**2.0
  ;;
- : float = 144.

That's kind of weird...

# -12.0**0.5;;
- : float = nan

Look at that link though... order of operations

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top