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

James Dennett jdennett at acm.org
Sun Jul 3 16:07:57 EDT 2005


Tom Anderson wrote:

> On Sun, 3 Jul 2005, George Sakkis wrote:
> 
>> "Tom Anderson" <twic at urchin.earth.li> wrote:
>>
>>>>> And finally, does Guido know something about arithmetic that i 
>>>>> don't, or
>>>>> is this expression:
>>>>>
>>>>> -1.0 ** 0.5
>>>>>
>>>>> Evaluated wrongly?
>>>>
>>>>
>>>> No, it is evaluated according to the rules of precedence. It is
>>>> equivalent to -(1.0**0.5). You are confusing it with (-1.0)**0.5 which
>>>> fails as expected.
>>>
>>>
>>> Ah. My mistake. I submit that this is also a bug in python's grammar.
>>> There's probably some terribly good reason for it, though.
>>
>>
>> How about 'conformance with standard mathematic notation', does this 
>> count for a terribly good reason?
> 
> 
> Yes. However, it's an excellent reason why python's precedence rules are 
> wrong - in conventional mathematical notation, the unary minus, used to 
> denote the sign of a literal number, does indeed have higher precedence 
> than exponentiation: -1^2 evaluates to 1, not -1.

No... that would mean that -x^2 == x^2 always, and we certainly
expect the lhs to always be negative or zero (for real x), and
the rhs to be non-negative.  Unary minus has lower precendence
than exponentiation, in conventional mathematics.  You'll often
see (-1)^n written in mathematics when we want the alternating
sequence +1, -1, +1, -1, ..., as -1^n wouldn't do it (giving
-1, -1, -1, -1).  -1^n evaluates to -1, for all non-zero integral
n.

> 
>> What would one expect to be the result of 5^2 - 2^2, 29 or 21?
> 
> 
> 21.

True, unambiguously; there are no negative numbers involved
at any time, just a simple binary minus.

> 
>> Would you expect 5^2 + - 2^2 to be different, even if you write it as 
>> 5^2 + -2 ^ 2 ?
> 
> 
> 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.

> 
>> White space is not significant in math AFAIK ;-)
> 
> 
> No, but there's a very big difference between unary and binary minus.

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.

-- James



More information about the Python-list mailing list