# What is the fastest way to obtain an infinity of the correct type?

This is related to Analogue of zero(T) for infinitiy - #5 by rdeits, but the suggestion

``````T(Inf)
``````

isn’t as fast as expected. In particular,

``````julia> @btime convert(Float16, \$(Ref(Inf))[]);
9.205 ns (0 allocations: 0 bytes)
``````

but I know statically that the answer must be `Inf16`, so ideally this shouldn’t carry out any conversion at all. Is there a faster way to compute this result?

1 Like

Is that really testing what you want? I’ve never used Refs in timing, have seen it recommended, but I’m not sure exactly what happens behind the scenes. I would do

``````julia> @btime convert(Float16, x) setup=(x=Inf)
1.691 ns (0 allocations: 0 bytes)
Inf16

julia> @code_llvm convert(Float16, Inf)
;  @ number.jl:7 within `convert`
define half @julia_convert_992(double %0) #0 {
top:
; ┌ @ float.jl:232 within `Float16`
%1 = fptrunc double %0 to half
; └
ret half %1
}
``````

which seems fast and comes down to a single llvm instruction.

Wouldn’t `typemax(T)` be a good way to get infinity for the types that support it, and for those that don’t you get the closest approximation?

3 Likes

In general, const prop would handle this.

``````julia> inf(::Type{T}) where {T} = convert(T, Inf)
inf (generic function with 1 method)

julia> @code_typed inf(Float16)
CodeInfo(
1 ─     return Inf16
) => Float16
``````

but yeah, I’d use `typemax(Float16)`.

``````julia> @code_typed typemax(Float16)
CodeInfo(
1 ─     return Inf16
) => Float16
``````

given it’s already defined and does what you want.

4 Likes