ShadowCat8
ShadowCat8

Reputation: 65

Need some clarification on the ** operator in Python

I wanted to start by asking here about this. This was given to me as part of an exercise at codeacademy.com and confused me for the better part of an hour.

Take a look at the following code block:

bool_one = 40 / 20 * 4 >= -4**2

Now, I evaluated that as being "8 >= 16" which is False.

However, the codeacademy.com terminal says it's True. When I started writing debug code lines, I found the issue was in how "-4**2" gets evaluated. When I run it on the terminal at CodeAcademy as well as on my local linux system, "-4**2" in Python comes out to "-16"... which is contrary to everything I have learned in all my math classes as well as every single calculator I have run it on. Whether I run it as "-4 * -4" or "-4^2" or even, using the "x^y" key, "-4 [x^y] 2", it still comes out as "16". So, how is python coming out with "-16" for "-4**2"?

Can someone please clarify this for me?

TIA.

Upvotes: 4

Views: 185

Answers (4)

sirius_x
sirius_x

Reputation: 183

-4**2 means -(4^2). First the 4 is being squared then its being multiplied with -1. -1(4^2) = -1(16) = -16.

If you want 16 as the answer then you have to put in (-4)**2.

>>> -4**2
-16
>>> (-4)**2
16

Upvotes: 0

vroomfondel
vroomfondel

Reputation: 3106

If you have -4 without parentheses, the negative sign is considered a unary operator which is essentially "multiply by negative one." (-4)**2 will be 16, because that is actually negative 4 squared, but -4**2 uses the normal order of operations (exponentiation before multiplication) and treats it as -(4**2).

Hope that helps!

Edit: to really understand operator precedence, take a look at this handy list in the docs:

http://docs.python.org/2/reference/expressions.html#operator-precedence

as you can see, - has less precedence than **

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213243

From the doc of Power Operator:

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

power ::=  primary ["**" u_expr]

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

Emphasis mine.

So, for getting the required result, you need to add parenthesis around -4.

>>> (-4) ** 2
16

Upvotes: 6

thagorn
thagorn

Reputation: 747

Python isn't evaluating it as (-4)^2 it is evaluating it as -(4^2).

>>> (-4)**2
16
>>>-4**2
-16

Upvotes: 1

Related Questions