11

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
marriam nayyer
  • 677
  • 5
  • 9
  • 19
  • 3
    Not sure about numpy but in pure python you can use `cmath.sqrt(-1)`. – Ashwini Chaudhary Jul 20 '13 at 21:26
  • Maybe this is beside the point, but I can't reproduce that issue exactly. I get `RuntimeWarning: invalid value encountered in sqrt` on the calculation, then `nan` is printed (which is a `numpy.float64`, to be clear). – wjandrea Jan 20 '22 at 22:14

6 Answers6

33

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
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
20

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
James Wright
  • 1,293
  • 2
  • 16
  • 32
David Zwicker
  • 23,581
  • 6
  • 62
  • 77
12

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

>>> import cmath
>>> cmath.sqrt(-1)
1j
abcd
  • 10,215
  • 15
  • 51
  • 85
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

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.

mnuizhre
  • 169
  • 7
0

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

Marcin
  • 48,559
  • 18
  • 128
  • 201
  • 2
    My guess is that @marriam is already using numpy, because `np.sqrt(-1)` results in the `invalid value encountered...` warning, while `math.sqrt(-1)` results in `ValueError: math domain error`. – Warren Weckesser Jul 20 '13 at 22:00
  • @WarrenWeckesser Either way, an appreciation of what complex numbers are will help her. – Marcin Jul 20 '13 at 22:01
0

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.

user2027202827
  • 1,234
  • 11
  • 29