[Tutor] a puzzle about -3**2 vs (-3)**2
Steven D'Aprano
steve at pearwood.info
Fri Jul 31 14:12:51 CEST 2015
On Thu, Jul 30, 2015 at 05:58:27PM -0700, D Wyatt wrote:
> I just read in a book a little while ago that ** trumps a negative
> sign?
Correct. Exponentiation has higher priority than subtraction, addition,
multiplication and division:
2+3**2 => 11 not 25
10-3**2 => 1 not 49
2*3**2 => 18 not 36
100/5**2 => 4 not 400
As you have discovered, it also has higher priority than unary minus so
that:
-3**2 => -(3**2) => -9 NOT (-3)**2 => 9
Mathematically, this is perfectly acceptable, and what we would
normally expect. In algebra, if we write:
-x²
we normally mean the negative of (x squared), not (negative x) squared,
which would be just x². So Python here agrees with standard mathematical
notation.
> 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.
Speaking as a maths tutor with about 20 years experience, and a B.Sc.
with a major in mathematics, I'm not sure I understand what you are
getting at. There is no mathematical difference between the inherent
negativeness of -1 and the arithmetic operation - 1 (unary minus
operator followed by 1).
Whichever way you treat it, we have to agree what it means. For example,
2x means 2 multiplied by x; but 23 doesn't mean 2 multiplied by 3. It
could if we wanted it to, but that would be inconvenient. Mathematicians
could define -3² as (-3)² = 9 if they wanted to, but generally they
don't, although there are exceptions. Consequently such expressions are
ambiguous and are best avoided. Although -x² never means -x squared,
it always means minus (x squared).
Python removes the ambiguity and has exponentiation always take priority
over other arithmetic operators, regardless of whether you consider - a
unary or binary operator, or an inherent part of the integer.
Although, for the record, the standard Python interpreter does NOT parse
an expression like -123 as "negative 123", but as "unary minus 123". In
practice this makes zero difference to the code.
--
Steve
More information about the Tutor
mailing list