What is the value of `-2^2`?
tldr: Depends on who you ask. And watch out for Excel – it takes the minority position that this is 4.
This is not meant to be a trick question – it is simply a matter of arbitrary choice in the order of operations.
So while PEMDAS is pretty well agreed upon, the relationship between unary minus and exponentiation is not. Different programming languages or spreadsheets handle it differently.
Here’s an example of how I ran into this bug. I was using Maxima, a free computer algebra system to solve a very complicated set of simultaneous equations. I then was copying this symbolic solution to a programming language of my own that I’ve been developing for engineering. I evaluated the expressions in both, and one of the evaluated expressions was completely different between the two.
I knew that the evaluated Maxima solution was correct based on the value. I then tried to copy the expression in Excel.
What then shocked me was that Excel matched my solution!
After evaluating what seemed like a thousand sub expressions, I found the culprit: -a^b
.
It turns out I had decided (without any thought) that unary minus should bind more tightly than exponentiation. Maxima, and from what I can tell, most other languages, has exponentiation at a higher precedence.
I proceeded to check how every language that I use handles this.
The only two that evaluated to 4 were Excel and the math
function in the fish shell.
Programs that evaluate -2^2
to 4:
- Excel
math
(fish shell)
Programs that evaluate -2^2
to -4:
Languages that this doesn’t apply to:
- C#: Uses
Math.Pow
method
As it appears -2^2
is generally evaluated to -4
, I updated my programming language grammar to match.
What this does mean though, is that you have to be careful in formula generation or copying and pasting expression like this into Excel.