在 Python 中,为什么负数的偶次幂仍然是负数? [英] In Python, why does a negative number raised to an even power remain negative?

查看:66
本文介绍了在 Python 中,为什么负数的偶次幂仍然是负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中

<预><代码>>>>我 = 3>>>-i**4-81

为什么 -i**4 不计算为 (-i)**4,而是计算为 -(i**4)?

我想有人可能会争辩说,提升到幂优先于 i 与减一的(隐式)乘法(即你应该阅读 -1*i**4).但是在我学习数学的地方,-i**nn 偶数和 i 正数,应该是正数.

解决方案

** 运算符比 Python 中的 - 运算符绑定得更紧密.如果你想覆盖它,你可以使用括号,例如(-i)**4.

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

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.

解决方案

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

这篇关于在 Python 中,为什么负数的偶次幂仍然是负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆