Efficiently type alias Float128, Float64, and Float32

Declare them as const, or pass them as arguments to your functions, which also makes the code much better because you don’t need two functions:

julia> init(n,T) = zeros(T,n,n)
init (generic function with 1 method)

julia> init(2,Float32)
2×2 Matrix{Float32}:
 0.0  0.0
 0.0  0.0

julia> init(2,Float64)
2×2 Matrix{Float64}:
 0.0  0.0
 0.0  0.0


It is more typical, though, that the types are derived from the type of input data being used, defined by some initial value somewhere else. For example, if you were to do a matrix-vector multiplication, where your vector is the input and the other is a random matrix of the same type, you could do:

julia> function f(x::AbstractVector)
           m = rand(eltype(x),length(x),length(x))
           return m*x
       end
f (generic function with 1 method)

julia> f(Float64[1.,2.,3.])
3-element Vector{Float64}:
 4.905931069551787
 3.091571412189738
 2.391551994266473

julia> f(Float32[1.,2.,3.])
3-element Vector{Float32}:
 3.374429
 3.7870452
 3.1641507


2 Likes