In Python, why does a negative number raised to an even power remain negative? [duplicate]

断了今生、忘了曾经 提交于 2021-01-27 03:51:35

问题


In Python

>>> i = 3  
>>> -i**4  
-81

Why is -i**4 not evaluated as (-i)**4, but as -(i**4)?

I suppose one could argue that raising to a power takes precedence over (implicit) multiplication of i with minus one (i.e. you should read -1*i**4). But where I learned math, -i**n with n even and i positive, should come out positive.


回答1:


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.

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




回答2:


The power operator (**) has a higher precedence than the unary negation (-) operator. -i**4 is evaluated as -(i**4) - i.e., you take 3 up to the power of four, which is 81, and then negate it, resulting in -81.




回答3:


You can use the pow() function from math.

import math
i = 3
math.pow(-i,4)

This will yield a positive value.

As stated here: Exponentials in python x.**y vs math.pow(x, y), this option (or just build in pow()) would be ideal if you want to always produce a float.




回答4:


You have to do (-i)**4 to get a positive result.

The *'s have higher priority than the '-'.

When in doubt, use parentheses. (or, as Amber suggested, refer to the language documentation)



来源:https://stackoverflow.com/questions/27726592/in-python-why-does-a-negative-number-raised-to-an-even-power-remain-negative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!