Converting Vector{Any} to Tuple of Floats

I am trying convert Vector{Any} to Tuple of Floats using function Tuple

julia> N = Any[5,2,3,4,4,5,0,1,5,6,9,7,8,9,9,20,2,2,6,6,5,4,5,6,8,5,4];

julia> Tuple{Float64}(N)
(5.0,)

How to convert the Vector N to Tuple of Floats in all elements (without loops)?

Tuple(Float64(x) for x in N)

5 Likes

This is very useful! Should be in the docs about tuples.

1 Like

And why not just

Tuple(1.0N)

?

1 Like

That allocates an extra Array.

julia> @btime Tuple(Float64(x) for x in N);
  5.474 Ī¼s (57 allocations: 1.42 KiB)

julia> @btime Tuple(1.0N);
  2.167 Ī¼s (90 allocations: 2.31 KiB)

1.5X more allocations with 2.5X more speed!

2 Likes

Interesting. On Julia 0.6.4 I get:

julia> @btime Tuple(Float64(x) for x in N);
  5.386 Ī¼s (65 allocations: 1.98 KiB)

julia> @btime Tuple(1.0N);
  20.139 Ī¼s (159 allocations: 4.16 KiB)

and on 1.0

julia> @btime Tuple(Float64(x) for x in N);
  6.836 Ī¼s (57 allocations: 1.42 KiB)

julia> @btime Tuple(1.0N); 
  2.660 Ī¼s (90 allocations: 2.31 KiB)

Other variants: Float64.(Tuple(N)) or Float64.(tuple(N...))

julia> @btime Float64.(Tuple($N))
  895.109 ns (5 allocations: 1.22 KiB)

julia> @btime Float64.(tuple($N...))
  840.075 ns (4 allocations: 912 bytes)

(on julia-0.7)

3 Likes

(Julia v1) those ^ benchmark best for various lengths of N, Real types
with (a) slightly better than (b)

(a) T1.(tuple(Vector{T2}ā€¦,)) where {T1<:Real, T2<:Real}

(b) T1.(Tuple(Vector{T2}) where {T1<:Real, T2<:Real}

Thank you very much for the example.
I have one more question. What is the use of the $ operator before N?

The $ is a particular feature of the BenchmarkTools.jl package, and only valid inside its macros (like @btime). The problem is that global variables in expressions often lead to type instability and extra allocations, and the $ is used to replace such variables/expressions via ā€œinterpolationā€. See here for a description of this feature.

when using BenchmarkTools to time myfunction(x), the x gets a $ in front of itself so the timing macro interprets it as if it were being used in a call rather than as a value given once, at the setup for benchmarking @btime myfunction($x)

1 Like