[Tutor] a puzzle about -3**2 vs (-3)**2
Todd
toddrjen at gmail.com
Fri Jul 31 11:07:31 CEST 2015
On Fri, Jul 31, 2015 at 2:58 AM, D Wyatt <fiberfolly at gmail.com> wrote:
> I just read in a book a little while ago that ** trumps a negative
> sign? I am struggling with the audacity of that as -1 is negative 1,
> NOT minus 1. How can an arithmetic operation trump an attribute of a
> negative integer? It truly makes no sense to me. Thank you for any
> enlightenment you can provide.
>
> Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32
> bit (In
> tel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> 3**2
> 9
> >>> (-3)**2
> 9
> >>> -3**2
> -9
> >>>
>
>
It is a matter of operator precedence. Certain operators are carried out
before others. See here:
https://docs.python.org/3/reference/expressions.html#operator-precedence
Negation has lower precedence than exponentiation. That means that the
exponentiation is carried out first, and negation is carried out second.
So "-3**2" is equivalent to "-(3**2)".
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
More information about the Tutor
mailing list