I would like for a function to return Inf in some cases. However, the type of Inf should depend on the floating type of the function arguments. That is, I would like the following
function f(x::R) where {R <: Real}
if # some condition
return Inf
end
end
to return Inf16 if R == Float16, Inf32 if R == Float32, Inf64 if R == Float64. However, there seem not to be a way of constructing Inf of a given type R <: Real, unlike e.g. zero. Is there a way to do this?
You can write R(Inf) or convert(R, Inf).
1 Like
R(Inf) doesn’t work for integers. Consider restricting R to AbstractFloat
function f(x::R) where {R <: AbstractFloat}
if # some condition
return R(Inf)
end
end
2 Likes
Right, depending on what you want you may want to restrict the method or call typemax which will be a typed infinity for float types.
You can also use
function f(x)
if stuff
return oftype(x, Inf)
end
...
end
which should lead to equivalent code, but is more compact if you don’t need R.
3 Likes
Wow, thanks a lot, all viable solutions. I marked Stefan’s as solution just because it is closest to what I was trying to do. But it’s all stuff to consider. Thanks again.