0

I have a question that is similar to the one posted here, but their solution is not working for this case. Here is a code snippet:

import numpy as np

x = np.arange(-5, 6)
y = np.sqrt(x)[np.logical_not(np.isnan(x))]
print(y)

Output

[       nan        nan        nan        nan        nan 0.
 1.         1.41421356 1.73205081 2.         2.23606798]
C:\Users\gmbra\Downloads\Python Programs\Mechanisms\scratch.py:4: RuntimeWarning: invalid value encountered in sqrt
  y = np.sqrt(x)[np.logical_not(np.isnan(x))]

The np.logical_not is not working as expected. What was expected was an array with no nan values. On a side note, how can I remove the warning given from trying to take the square root of a negative number?

I would like to add that I will be performing other operations which will produce nan values. I just want to ignore those.

Gabe Morris
  • 804
  • 4
  • 21

1 Answers1

0

ufunc like np.sqrt take a where parameter that lets us select elements to evaluate. We need to provide a out as well.

In [783]: x = np.arange(-5,5)
In [784]: out=np.zeros(x.shape)
In [785]: np.sqrt(x, where=x>=0, out=out)
Out[785]: 
array([0.        , 0.        , 0.        , 0.        , 0.        ,
       0.        , 1.        , 1.41421356, 1.73205081, 2.        ])
In [786]: out
Out[786]: 
array([0.        , 0.        , 0.        , 0.        , 0.        ,
       0.        , 1.        , 1.41421356, 1.73205081, 2.        ])

This approach keeps the same size, as opposed to returning just the non-zero.

And for completeness compare sqrt with integer argument and one with complex input:

In [787]: np.sqrt(x)
<ipython-input-787-0b43c7e80401>:1: RuntimeWarning: invalid value encountered in sqrt
  np.sqrt(x)
Out[787]: 
array([       nan,        nan,        nan,        nan,        nan,
       0.        , 1.        , 1.41421356, 1.73205081, 2.        ])
In [788]: np.sqrt(x.astype(complex))
Out[788]: 
array([0.        +2.23606798j, 0.        +2.j        ,
       0.        +1.73205081j, 0.        +1.41421356j,
       0.        +1.j        , 0.        +0.j        ,
       1.        +0.j        , 1.41421356+0.j        ,
       1.73205081+0.j        , 2.        +0.j        ])
hpaulj
  • 221,503
  • 14
  • 230
  • 353