# [Tutor] a puzzle about -3**2 vs (-3)**2

Steven D'Aprano steve at pearwood.info
Sat Aug 1 18:43:20 CEST 2015

```Hi Deb,

On Fri, Jul 31, 2015 at 10:20:50AM -0700, D Wyatt wrote:
> <snip>
> >
> > This matches the precedence rules for written mathematics, where negation
> > has a lower precedence than exponentiation as well.  So python is doing the
> > correct thing here mathematically.  See, for example,
> > http://mathforum.org/library/drmath/view/53194.html
[...]
> That is just so counterintuitive, and I've never run into this in any
> mathematics I have taken.  Now I'm going to have to research this
> further, from a mathematics standpoint.

You have inspired me to do a bit more research.

I've found at least three programming languages that behave as you
expect: the programming language "bc", Xion, and Microsoft Excel
formulae. For instance, Xion evaluates -3^2 as 9.

And proving that you're damned if you do and damned if you don't, here
is a bug report filed against Excel, stating that -2^2 returns 4 instead
of the expected result -4:

https://support.microsoft.com/en-gb/kb/kbview/132686

My favourite scientific calculator, the HP 48GX, uses Reverse Polish
Notation by default and so the question of operator precedence doesn't
come up. But it also has an optional algebraic mode, and '-2^2'
evaulates as -4.

Javascript doesn't have a power operator. Neither does C, one of the
most widely-used languages in the world.

Ruby agrees with Python:

irb(main):001:0> -3**2
=> -9

According to Wikipedia:

https://en.wikipedia.org/wiki/Order_of_operations

some scientific journals now treat multiplication as a higher precedence
than division with a / so that 1/2x equals 1/(2x), not (1/2)x.

There's an interesting study done here:

"Developer beliefs about binary operator precedence"

http://www.knosof.co.uk/cbook/accu06.html

which suggests that even professional programmers get operator
precedence wrong at a high rate. (The study found a 33% error rate.)

The bottom line is, there is no universal right or wrong answer for the
precedence rules for operators, although some rules are less right than
others.

--
Steve
```