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?
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.
– Jefferson Carvalho
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 x². If that were true an equation that is usually written -x² = -1, would have to be written as -(x²) = -1.
– Miguel Angelo