Julia test if number is NaN

Hello,
I have a variable that is non a number:

julia> Bs
NaN

and I have written a test to check for it:

julia> if Bs == NaN
           println("NON A NUMBER! Bs = ", Bs)
       else
           println("OK, Bs is ", Bs)
       end
OK, Bs is NaN

julia>

Since NaN is a number

julia> typeof(NaN)
Float64
julia> NaN isa Number
true

how can I check if a variable is not a number? If I check if NaN is a digit a get an error:

julia> isdigit(NaN)
ERROR: MethodError: no method matching isdigit(::Float64)
Closest candidates are:
  isdigit(::AbstractChar) at strings/unicode.jl:347
Stacktrace:
 [1] top-level scope at none:0

this is not elegant and might cause problems in the script. Is there a proper way ot check if a variable is NaN?
Thank you

1 Like

isnan

7 Likes

Yep! So simple! Thank you.

julia> if isnan(Bs)
           println("NON A NUMBER! Bs = ", Bs)
       else
           println("OK, Bs is ", Bs)
       end
NON A NUMBER! Bs = NaN

Note that you can generally find something like this with eg apropos("NaN").

4 Likes

That happened because, by definition of NaN, nothing is equal to a NaN, not even itself

julia> Bs = NaN;

julia> Bs == NaN
false

julia> NaN == NaN
false
3 Likes

I didn’t know about apropos. Cool!