Reputation: 697
When I take the square root of -1 it gives me an error:
invalid value encountered in sqrt
How do I fix that?
from numpy import sqrt
arr = sqrt(-1)
print(arr)
Upvotes: 12
Views: 34983
Reputation: 1058
This can be done by specifying the dtype
as complex in numpy's sqrt
function
from numpy import sqrt
arr = sqrt(-1, dtype=np.complex128)
print(arr)
Upvotes: 0
Reputation: 24338
I just discovered the convenience function numpy.emath.sqrt
explained in the sqrt documentation. I use it as follows:
>>> from numpy.emath import sqrt as csqrt
>>> csqrt(-1)
1j
Upvotes: 21
Reputation: 169
The latest addendum to the Numpy Documentation here, adds the command numpy.emath.sqrt
which returns the complex numbers when the negative numbers are fed to the square root sign in a operation.
Upvotes: 1
Reputation: 304503
You need to use the sqrt from the cmath module (part of the standard library)
>>> import cmath
>>> cmath.sqrt(-1)
1j
Upvotes: 12
Reputation: 1234
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.
Upvotes: 0
Reputation: 114976
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
Upvotes: 36
Reputation: 49886
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
Upvotes: 0