如何使用python取-1的平方根?

时间:2013-07-20 21:16:46

标签: python numpy

当我取-1的平方根时,它给出了一个错误:

  

在sqrt中遇到无效值

我该如何解决?

/////////
arr=sqrt(-1)
print(arr)
OUTPUT

5 个答案:

答案 0 :(得分:26)

为避免invalid value警告/错误,numpy的sqrt函数的参数必须复杂:

In [8]: import numpy as np

In [9]: np.sqrt(-1+0j)
Out[9]: 1j

@AshwiniChaudhary在评论中指出,你也可以使用cmath标准库:

In [10]: cmath.sqrt(-1)
Out[10]: 1j

答案 1 :(得分:8)

您需要使用cmath模块(标准库的一部分)

中的sqrt
>>> import cmath
>>> cmath.sqrt(-1)
1j

答案 2 :(得分:8)

我刚刚发现了sqrt documentation中解释的便捷函数numpy.lib.scimath.sqrt。我用它如下:

>>> from numpy.lib.scimath import sqrt as csqrt
>>> csqrt(-1)
1j

答案 3 :(得分:0)

-1的平方根不是实数,而是虚数。 IEEE 754无法表示虚数。

numpy支持复杂的数字。我建议你使用它:http://docs.scipy.org/doc/numpy/user/basics.types.html

答案 4 :(得分:0)

其他人可能会提出更理想的方法,但只是为了添加到对话中,你总是可以将任何小于0的数字(你想要的sqrt值,在本例中为-1)乘以-1,然后取平方的。只要知道你的结果是虚构的。