ValueError:负数不能被提升到分数幂 [英] ValueError: negative number cannot be raised to a fractional power

查看:55
本文介绍了ValueError:负数不能被提升到分数幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在终端中尝试此操作时

<预><代码>>>>(-3.66/26.32)**0.2

我收到以下错误

回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:负数不能被提升到分数幂

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

<预><代码>>>>(-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回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError:负数不能被提升到分数幂

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

<预><代码>>>>(-3.66/26.32 + 0j)**0.2(0.5452512685753758+0.39614823506888347j)

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

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?

解决方案

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.

这篇关于ValueError:负数不能被提升到分数幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆