python - 值错误 : negative number cannot be raised to a fractional power

标签 python

当我在终端尝试这个时

>>> (-3.66/26.32)**0.2

我收到以下错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power

但是,我可以分两步完成,例如,

>>> (-3.66/26.32)
-0.13905775075987842
>>> -0.13905775075987842 ** 0.2
-0.6739676327771593

为什么会有这种行为?单行解决这个问题的方法是什么?

最佳答案

求幂优先于一元减号。

所以你有 -(0.13905775075987842 ** 0.2) 而不是 (-0.13905775075987842) ** 0.2 如你所料:

>>> -0.13905775075987842 ** 0.2
-0.6739676327771593
>>> (-0.13905775075987842) ** 0.2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power

如果你想让它工作,你应该写 (-3.66/26.32 + 0j)**0.2

>>> (-3.66/26.32 + 0j)**0.2
(0.5452512685753758+0.39614823506888347j)

或者按照@TimPietzcker 的说明切换 Python 3。

关于python - 值错误 : negative number cannot be raised to a fractional power,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17747124/

相关文章:

Python Selenium 一个隐藏框架,有时会与 java 脚本断言一起出现

python - 使用 python 和 pytables 处理大文件

python - 创建我自己的协程以与 asyncio 一起使用

c++ - 在 Boost.Python 中沮丧

python - 避免 Pylint 警告 E1101 : 'Instance of .. has no .. member' for class with dynamic attributes

python - Flask-PyMongo : how come "self._Collection__database"?

python - 尽管有 __init__.py,但在非包错误中尝试相对导入

python - 如何在keras CNN中使用黑白图像?

python - 计算素数并附加到列表

python - Pandas 缺失数据