10

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
  • 23,210
  • 7
  • 49
  • 68
marriam nayyer
  • 667
  • 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

5 Answers5

32

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
  • 102,583
  • 19
  • 173
  • 194
18

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
David Zwicker
  • 22,266
  • 6
  • 57
  • 74
12

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

>>> import cmath
>>> cmath.sqrt(-1)
1j
dbliss
  • 9,270
  • 15
  • 46
  • 80
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
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
  • 46,667
  • 17
  • 117
  • 197
  • 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,214
  • 10
  • 29