0

why when i write -2 ** 2 in python the result is -4 but my lambda function is returning 4 anyone could explain why this is happening

Code result

two = lambda: 2
sqr = lambda x: x * x
pwr = lambda x, y: x ** y
for a in range(-2, 3):
    print(sqr(a), end=" ") 
    print(a,"**",two(),"=",pwr(a, two()))
Flàyn
  • 23
  • 5
  • What do you mean by "we all know?" Why do you expect `-4` as an answer? Negative 2 to the 2nd power is 4. – gen_Eric Sep 29 '21 at 17:08
  • 4
    "We all know that -2 ** 2 = -4" Only because of precedence. `-2 ** 2` is `-(2 ** 2)`, which is indeed -4. But `(-2) ** 2` is 4 and that's what your lambda calculates when applied to the arguments `-2` and `2`. – sepp2k Sep 29 '21 at 17:11
  • @sepp2k You're correct, and the binding of Python's `**` operator is demonstrably confusing enough to warrant an explanation in an answer. For instance, the fact that `-2**2` is `-4` because `**` has higher precedence on the left, but simultaneously `2**-2` is valid and equal to `0.5` because the unary minus is on the right of `**` – kcsquared Sep 29 '21 at 17:22

1 Answers1

0

The ** operator binds more tightly than the - operator does in Python. If you want to override that, you'd use parentheses, e.g. (-i)**4

Jayakrishnan
  • 563
  • 5
  • 13