当我在终端尝试这个时
>>> (-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/