Why does “**” bind more tightly than negation?

喜欢而已 提交于 2019-12-21 08:49:33

问题


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?


回答1:


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.




回答2:


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.




回答3:


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!




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/936904/why-does-bind-more-tightly-than-negation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!