Type stability for scalars

For type stability my current code is:

eltype(x)(0.5)

Please advise, is there a simpler solution if x is a scalar?

1 Like

To get the type of x you can use typeof(x).
To convert 0.5 to the type of x you can use oftype(x, 0.5).

5 Likes

Thank you very much!

Just one more question.
Is there the slightest difference in code efficiency for the three versions?
(I see no difference after top:, but what happens in define?)

julia> x = 1f0
1.0f0

julia> @code_llvm typeof(x)(0.5)

; Function Attrs: uwtable
define float @jlsys_Type_56602(i8**, double) #0 !dbg !5 {
top:
  %2 = fptrunc double %1 to float
  ret float %2
}

julia> @code_llvm eltype(x)(0.5)

; Function Attrs: uwtable
define float @jlsys_Type_56602(i8**, double) #0 !dbg !5 {
top:
  %2 = fptrunc double %1 to float
  ret float %2
}

julia> @code_llvm oftype(x,0.5)

; Function Attrs: uwtable
define float @julia_oftype_64020(float, double) #0 !dbg !5 {
top:
  %2 = fptrunc double %1 to float
  ret float %2
}

I guess there should be no difference in performance. When I use @code_native the generated code is identical although it references to a different file.

Thank you again.
It is a peace of mind that I am free to choose the preferred syntax.