How can I take the square root of -1 using python?

前端 未结 5 444
天涯浪人
天涯浪人 2020-12-06 17:59

When I take the square root of -1 it gives me an error:

invalid value encountered in sqrt

How do I fix that?

///         


        
相关标签:
5条回答
  • 2020-12-06 18:05

    The square root of -1 is not a real number, but rather an imaginary number. IEEE 754 does not have a way of representing imaginary numbers.

    numpy has support for complex numbers. I suggest you use that: http://docs.scipy.org/doc/numpy/user/basics.types.html

    0 讨论(0)
  • 2020-12-06 18:09

    You need to use the sqrt from the cmath module (part of the standard library)

    >>> import cmath
    >>> cmath.sqrt(-1)
    1j
    
    0 讨论(0)
  • 2020-12-06 18:10

    Others have probably suggested more desirable methods, but just to add to the conversation, you could always multiply any number less than 0 (the value you want the sqrt of, -1 in this case) by -1, then take the sqrt of that. Just know then that your result is imaginary.

    0 讨论(0)
  • 2020-12-06 18:13

    I just discovered the convenience function numpy.lib.scimath.sqrt explained in the sqrt documentation. I use it as follows:

    >>> from numpy.lib.scimath import sqrt as csqrt
    >>> csqrt(-1)
    1j
    
    0 讨论(0)
  • 2020-12-06 18:15

    To avoid the invalid value warning/error, the argument to numpy's sqrt function must be complex:

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

    As @AshwiniChaudhary pointed out in a comment, you could also use the cmath standard library:

    In [10]: cmath.sqrt(-1)
    Out[10]: 1j
    
    0 讨论(0)
提交回复
热议问题