Simple noob question: I don't understand how squared equations work


How is it that -3 * -3 = 9, but -3^2 = -9? I can understand -(3^2) equaling -9, but according to Please Excuse My Dear Aunt Sally, exponents come before multiplication (in reference to -3^2 = -9). Side note: (-3)^2 does = 9.

puzzled noob


See the table here:

Julia’s got quite a few more operations than just the six enumerated in PEMDAS. Specifically, unary minus is itself an operation that fits between “excuse my”.


Thank you mbauman. I’m not sure why the developers chose to implement Julia this way, but the output makes sense now. [Disclaimer: I know extremely little about development]


I was wondering GreyMoth, how would you intrepret each of the three mathematical expression below?

A: “5-3^2”

B: “0-3^2”

C: “-3^2”

Because B and C are exactly the same mathematically.


Julia matches the way mathematicians write expressions. It makes the rules a little subtler, but when someone writes -3^2 on paper (or in LaTeX) they do not mean (-3)^2, they mean -(3^2). Also, this shouldn’t be all that surprising since subtraction—or negation, technically I’m this case—has lower precedence than exponentiation. I guess you are interpreting -3 as a negative literal rather than interpreting the - as a minus operator. The later is the interpretation that matches mathematical notation and the one which Julia uses.


Frankly, it should not matter. Most people rely on maybe the 2–3 most obvious precedence order pairs (eg things like + vs *), which are more or less the same in every language.

The rest should never be relied on, especially for people who use more than 1 language, because it can result in very subtle bugs that can only be caught by painstakingly looking up the exact rules. When in doubt, use ()s. Always be in doubt.


The Wikipedia page on order of operations explicitly calls out this exact example:

There are differing conventions concerning the unary operator (usually read “minus”). In written or printed mathematics, the expression −3^2 is interpreted to mean 0 − (3^2) = − 9.

So what we’re doing here is not exactly controversial.

Basically, there are two possible reasonable interpretations of -3^2:

  1. ^ applied to the -3 and 2, or
  2. - applied to ^ applied to 3 and 2.

Julia chooses the interpretation that matches standard mathematical convention. Moreover, if we used the first (non-standard) interpretation, then -3^2 would produce a different result than x = 3; -x^2 since -x is not a literal so only the second interpretation is possible. The two expressions would parse differently and the former would produce 9 while the latter would produce -9, which certainly seems like a bad situation.