![](/img/trans.png)
[英]ValueError: negative number cannot be raised to a fractional power in iterable list - Python
[英]ValueError: negative number cannot be raised to a fractional power
當我在終端嘗試這個
>>> (-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 3,它會自動將結果提升為復數:
>>> (-3.66/26.32)**0.2
(0.5452512685753758+0.39614823506888347j)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.