power TypeErrors

Bengt Richter bokr at oz.net
Tue Nov 5 20:58:56 EST 2002


On Tue, 5 Nov 2002 16:15:09 -0500, Carl Banks <imbosol at vt.edu> wrote:

>anton wilson wrote:
>> I'm trying to understand the possible type errors for **
>> 
>> The language reference states that
>> 
>> 
>> The power operator has the same semantics as the built-in pow() function, 
>> when called with two arguments: it yields its left argument raised to the 
>> power of its right argument. The numeric arguments are first converted to a 
>> common type. The result type is that of the arguments after coercion; if the 
>> result is not expressible in that type (as in raising an integer to a 
>> negative power, or a negative floating point number to a broken power), a 
>> TypeError exception is raised. 
>> 
>> 
>> 
>> I'm running code such as: 
>> 
>> 1 ** -2
>> -1.2 ** 0.5
>> 
>> and there is no type error.
>> 
>> How do I generate a type error?
>
>
>(-1.2) ** 0.5
>
>It seems strange at first, but the ** operator is stronger than the
>negative sign: Python sees "-1.2 ** 0.5" as "-(1.2**0.5)".  Of course,
>that's the convention in mathematical notation.
>
>1 ** -2 does give me a type error.
>
?? No prob on 2.2.2:

 >>> 1 ** -2
 1.0

But this makes wonder about working with complex numbers, where
name bindings might be to plain real negatives as well as complex
numbers (as easy to do as binding to integers and floats, which makes
for the '/' problem) yet you might want the same for
 >>> a = -4.0+0j
 >>> b = -4.0
 >>> a ** 0.5
 (1.2246063538223773e-016+2j)
 >>> b ** 0.5
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 ValueError: negative number cannot be raised to a fractional power

It seems like a problem analogous to the true division problem,
except that fewer people expect complex results.

I wouldn't want complex results all the time, but I can see wanting
to run that way in a limited context.

Which comes down again to whether there should be some kind of general
mechanism to control such modes of operation within scopes such as
function bodies or statement suites (indented blocks).

Regards,
Bengt Richter



More information about the Python-list mailing list