ValueError: negative number cannot be raised to a fractional power

匿名 (未验证) 提交于 2019-12-03 02:12:02

问题:

When I tried this in terminal

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

I got the following error

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

However, I am able to do this in two steps like,

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

Why this behaviour? What is the way to solve this in single line?

回答1:

Raising to a power takes precedence over the unary minus sign.

So you have -(0.13905775075987842 ** 0.2) and not (-0.13905775075987842) ** 0.2 as you expect:

>>> -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 

If you want it to work you should write (-3.66/26.32 + 0j)**0.2

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

Or switch Python 3 as noted by @TimPietzcker.



回答2:

Switch to Python 3 which automatically promotes the result to a complex number:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!