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

新手上路,请多包涵

当我取 -1 的平方根时,出现错误:

sqrt 中遇到无效值

我该如何解决?

 from numpy import sqrt
arr = sqrt(-1)
print(arr)

原文由 marriam nayyer 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 526
2 个回答

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

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

原文由 John La Rooy 发布,翻译遵循 CC BY-SA 4.0 许可协议

为了避免 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

原文由 Warren Weckesser 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏