math.nroot [was Re: A brief question.]

James Dennett jdennett at
Mon Jul 4 22:04:40 CEST 2005

Steven D'Aprano wrote:

> James Dennett wrote:
>> > Yes: 5^2 + -2^2 is 29, however you write it.
>> *If* you take -2 as a number, but not if you take the number
>> as 2 and the unary minus as an operator with lower precedence
>> than exponentiation.
> [snip]
>> Not in this respect.  However, the question is whether that's
>> a unary -, which binds lower than exponentiation in most systems,
>> or part of the negative number minus 2.
> In Python, all numbers are positive. -2 is a unary minus in front of 2.

Indeed, as I hoped was clear from the rest of my post.  When
we're discussing what the rules of Python *should* be, however,
it's necessary to step back and not assume that the rules of
Python are "right", whatever we might mean by that.

I was illustrating that the choice made by Python in this
respect, i.e., of viewing "-2" as an expression where unary
minus applies to the number 2, naturally leads to
5**2 + -2**2 being evaluated as 21 (because of the precedence
of unary minus), whereas taking "-2" as a number would lead
to the answer 29 (which is not what Python gives).

That said, Python's choice is consistent with conventional
mathematical notation, which is one reason not to lex -2 as
a number in a language with an infix exponentiation operator.

-- James

More information about the Python-list mailing list