Selecting NaN for different machine precision

question

#1

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)
end

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


#2

Something like this?

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

#3

#4

Thank you @joshday :slight_smile:


#5

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:


#6

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


#7

Just fixing a small issue, it should look like:

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

#8

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.


#9

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