Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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)
like image 916
marriam nayyer Avatar asked Jul 20 '13 21:07

marriam nayyer


3 Answers

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
like image 138
David Zwicker Avatar answered Nov 01 '22 04:11

David Zwicker


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
like image 33
Warren Weckesser Avatar answered Nov 01 '22 05:11

Warren Weckesser


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

>>> import cmath
>>> cmath.sqrt(-1)
1j
like image 12
John La Rooy Avatar answered Nov 01 '22 04:11

John La Rooy