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

梦想的初衷 提交于 2019-12-04 03:04:42

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.

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

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