Little doubt with numerical operations

3

I was doing a function in python that returns me the results (x 'ex) of the bhaskara formula, just to train the logic a little bit. more, but it made me curious.

If I raise a negative number squared, the expected result is positive, right?

>>> -7 ** 2
-49

Not what happens if I do the above. However, if I assign -7 to a variable x , for example, and try to raise x to the square ...

>>> x  = -7
>>> x ** 2
49

... the result comes out as expected. Why did not python do the operation correctly from the first mode?

    
asked by anonymous 14.04.2015 / 18:16

1 answer

5

It seems that the ** operator has higher precedence than the unary operator - , ie first the interpreter calculates the power and then the negative one. So the expression -7 ** 2 would be equivalent to -(7 ** 2) , which results in -49 .

If you think hard, this is usually the case when we are operating mathematical expressions on a piece of paper:

  • -7 2 is actually -49
  • (- 7) 2 that would be 49
14.04.2015 / 18:21