【问题标题】:How can I take the square root of -1 using python?如何使用 python 取 -1 的平方根?
【发布时间】:2013-07-20 21:16:45
【问题描述】:

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

在 sqrt 中遇到无效值

我该如何解决这个问题?

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

【问题讨论】:

  • 不确定 numpy 但在纯 python 中你可以使用cmath.sqrt(-1)
  • 也许这不是重点,但我无法准确重现该问题。我在计算中得到RuntimeWarning: invalid value encountered in sqrt,然后打印nan(要清楚的是numpy.float64)。

标签: python numpy


【解决方案1】:

我刚刚发现了sqrt documentation 中解释的便利功能numpy.lib.scimath.sqrt。我使用它如下:

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

【讨论】:

  • 这是 2020 年总体上更好的答案。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      其他人可能提出了更理想的方法,但只是为了增加对话,您总是可以将任何小于 0 的数字(您想要的 sqrt 的值,在这种情况下为 -1)乘以 -1,然后取的平方。然后就知道你的结果是虚构的。

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

        • 我的猜测是@marriam 已经在使用numpy,因为np.sqrt(-1) 导致invalid value encountered... 警告,而math.sqrt(-1) 导致ValueError: math domain error
        • @WarrenWeckesser 不管怎样,了解复数是什么对她有帮助。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-23
        • 2017-07-05
        • 1970-01-01
        • 2022-12-04
        • 2019-06-01
        • 1970-01-01
        相关资源
        最近更新 更多