ValueError:负数不能提高到小数幂
当我在终端尝试这个
>>> (-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。