Analogue of zero(T) for infinitiy

How do I get the infinity corresponding to a type? Is there an analog of zero(T)? Something like:

inf(Float16)

Here is how I would define it myself:

function inf(::Type{T})::T where T
    one(T) / zero(T)
end

Is there a better way?

T(Inf). For example, Float16(Inf).

3 Likes

If we can do T(0), what’s the point of zero(T)?

For any subtype of Number, zero(T) is just a shorthand for convert(T, 0). See: https://github.com/JuliaLang/julia/blob/6a23e234e6cc5b4361b5f88614a9ed423dc2c12a/base/number.jl#L238

And for any type T, if you haven’t defined a constructor T(x), then it will also fall back to convert(T, x). See: https://github.com/JuliaLang/julia/blob/6a23e234e6cc5b4361b5f88614a9ed423dc2c12a/base/sysimg.jl#L114

So zero(T) is strictly equivalent to T(0). Then why do we need zero(...)?

Because zero works for types that are not numbers. e.g. matrices. Any type supporting + should also define a zero function to return the additive identity.

In contrast, Inf is pretty much only meaningful for numeric types, specifically floating-point types.

5 Likes