Function Repository Resource:

NaNQ

Source Notebook

Test if a numeric value is an IEEE 754 NaN

Contributed by: Ting Sun

ResourceFunction["NaNQ"][x]

gives True if real number x is an IEEE 754 NaN and False otherwise.

Details

IEEE 754 NaN values are usually imported as real numbers via LibraryLink or other extenral numeric systems (e.g. NumPy).
Some usages should be converted to Indeterminate prior to further computation.

Examples

Basic Examples (1) 

Introduce an IEEE 754 NaN value and test it:

In[1]:=
xNaN = ExternalEvaluate["Python", "import numpy as np; np.array([np.nan])"] // Normal // First
Out[1]=
In[2]:=
ResourceFunction["NaNQ"][xNaN]
Out[2]=

Applications (1) 

Detect IEEE 754 NaN values and replace them with Indeterminate for further computation:

In[3]:=
xArray = ExternalEvaluate["Python", "import numpy as np; x=np.random.random_sample([5,4]);x[[1,3],[2,2]]=np.nan;x"] // Normal;
xArray /. x_?ResourceFunction["NaNQ"] :> Indeterminate
Out[4]=

Possible Issues (2) 

Direct computation involving NaN values may give unexpected results:

In[5]:=
xArray = ExternalEvaluate["Python", "import numpy as np; x=np.random.random_sample([5,4]);x[[1,3],[2,2]]=np.nan;x"] // Normal;
xArray + 1 - xArray
Out[5]=

NaNs should be replaced by Indeterminate for further computation:

In[6]:=
With[{xArrayCorrected = xArray /. x_?ResourceFunction["NaNQ"] :> Indeterminate}, xArrayCorrected + 1 - xArrayCorrected]
Out[6]=

Publisher

Ting Sun

Version History

  • 1.0.0 – 26 April 2021

Related Resources

License Information