semantics of ** (unexpected/inconsistent?)

The Music Guy FearsomeDragonfly at gmail.com
Sun Nov 29 20:10:00 EST 2009


It's just like in algebra. You evaluate exponents before the - which, after
all, is just another way to write -1, or times-negative-one. However, a
variable with a negative value is not the same as a value that is being
multiplied by a negative.

-3 ** 2   =   (-1)(3)^(2)  in algebraic terms. Exponents first, then
multiplication.

However,

x ** 2 = (x)^(2) = (-3)^(2)

regardless of the value of x which, in this case, is -3. When you multiply a
negative by itself, you get a positive.

In short, the ** operator appears to have a higher precedence than the -
operator, based on your results.


On Sun, Nov 29, 2009 at 6:39 PM, Esmail <ebonak at hotmail.com> wrote:

> Ok, this is somewhat unexpected:
>
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
>
> >>> -3**2
> -9
>
> >>> x = -3
>
> >>> x**2
> 9
> >>>
>
> I would have expected the same result in both cases.
>
> Initially I would have expected -3**2 to yield 9, but I can accept
> that ** binds tighter than the unary -, but shouldn't the results
> be consistent regardless if I use a literal or a variable?
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091129/dcf476a4/attachment.html>


More information about the Python-list mailing list