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


#1

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.

Sincerely,
puzzled noob


#2

See the table here:

https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity-1

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”.


#3

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]


#4

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.


#5

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.


#6

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.


#7

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.