Selecting NaN for different machine precision



Currently I am defining the following function to get type stability a la one and zero for single and double precision:

nan(::Type{Float32}) = NaN32
nan(::Type{Float64}) = NaN64

Inside of my function I call it with the appropriate type:

function f(a::T) where {T<:AbstractFloat}
  a > zero(T) ? a : nan(T)

Is it possible to extend this definition to all AbstractFloat types? How one would define a fallback method for other number of bits?


Something like this?

nan{T<:AbstractFloat}(::T) = T(NaN)



Thank you @joshday :slight_smile:


Hi @yuyichao, is there any penalty in using the syntax T(NaN)? Is it performing a conversion between types?

Thanks for the link :slight_smile:


For all base types there’s no difference. If there is ever a situation the two disagrees the convert should be the correct one.


Just fixing a small issue, it should look like:

nan{T<:AbstractFloat}(::Type{T}) = T(NaN)


In general, defining synonyms for basic Julia constructs will just make your code harder for others to read. It’s just as compact to use T(NaN) as nan(T), so you might as well stick with the former.


Fully agree @stevengj, I will step back and remove the definition from the package :thumbsup: