I'm getting a strange result when squaring -1 in idle. What's going on?
Unexpected result:
>>>| -1 ** 2
>>>| -1
Expected result:
>>>| pow(-1,2)
>>>| 1
>>>| my_var = -1
>>>| my_var **= 2
>>>| my_var
>>>| 1
CodePudding user response:
Operator precedence (the - is a unary minus operator):
>>> -1 ** 2
-1
>>> -(1 ** 2)
-1
>>> (-1) ** 2
1
CodePudding user response:
This happens occurs because of Precedence Operators:
()Parentheses**Exponentx,-x,~xUnary plus, Unary minus, Bitwise NOT*,/,//,%Multiplication, Division, Floor division, Modulus,-Addition, Subtraction
you can get what you want like below, In The question first ** then compute Unary minus for solving you need to use higher precedence like () Parentheses.
>>> (-1) ** 2
1
