Need to refine ** operator in Python

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

Take a look at the following block of code:

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

Now I rated it as "8> = 16", which is False.

However, the codeacademy.com terminal says True. When I started writing lines of debugging code, I found that the problem is how "-4 ** 2" is evaluated. When I run it on the terminal in CodeAcademy, as well as on my local Linux system, "-4 ** 2" in Python goes to "-16" ... which contradicts everything that I learned in all my math classes and also every calculator on which I ran it. I run it as "-4 * -4" or "-4 ^ 2" or even using the key "x ^ y", "-4 [x ^ y] 2", it still comes out as "16". So what does python look like with "-16" for "-4 ** 2"?

Can someone clarify this for me?

TIA.

+4
source share
4 answers

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

Hope this helps!

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

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

as you can see, it has less priority than **

+3
source

From the Power Operator document:

The power operator communicates more rigidly than the unary operators on it left; it binds less tightly than the unary operators on the right. syntax:

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

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

Emphasis is mine.

So, to get the desired result you need to add parentheses around -4 .

 >>> (-4) ** 2 16 
+6
source

Python does not rate it as (-4) ^ 2, it evaluates it as - (4 ^ 2).

 >>> (-4)**2 16 >>>-4**2 -16 
+1
source

-4 ** 2 means - (4 ^ 2). First 4 is squared, and then multiplied by -1. -1 (4 ^ 2) = -1 (16) = -16.

If you want 16 as the answer, then you need to enter (-4) ** 2.

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

Source: https://habr.com/ru/post/1495806/


All Articles