Small doubt with numerical operations

Asked

Viewed 159 times

4

I was doing a python function that gives me the results (x' and x") of bhaskara formula, just to train the logic a little bit. And playing a little bit in the shell, I ended up discovering something strange. It’s no big deal, but it made me curious.

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

>>> -7 ** 2
-49

It’s not what happens if I do the above way. However, if I assign the -7 to a variable x, for example, and try to raise x squared...

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

...the result is as expected. Why python did not perform the operation correctly in the first mode?

1 answer

6


From the looks of the operator ** has greater precedence than the unary operator -, that is, first the interpreter calculates the power and then the negative. So the expression -7 ** 2 would be equivalent to -(7 ** 2), which results in -49.

If you think about it, that’s what usually happens when we’re operating mathematical expressions on a piece of paper:

  • -72 is in fact -49
  • (-7)2 that yes would be 49
  • I understood, but I still find it strange, because I didn’t explain the parentheses to leave the negative sign out. I even thought this might be some kind of bug.

  • 1

    It is a matter of mathematical notation itself. Power has greater precedence. If the negative sign had greater precedence, then -x² would equal (-x)² which would equal . If that were true an equation that is usually written -x² = -1, would have to be written as -(x²) = -1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.