Is there an easy way to change the eltype of ranges?

For example:

julia> r = 2.0:3.0
2.0:1.0:3.0

julia> eltype(r)
Float64

julia> Float32.(r)
2-element Array{Float32,1}:
 2.0
 3.0

This creates a Vector from the range. Is there a way to obtain another range (I don’t care about potential accuracy loss in the conversion)? I am looking for something a bit less verbose than calling range directly:

julia> range(Float32(first(r)), Float32(last(r)), length = length(r))
2.0f0:1.0f0:3.0f0

Maybe

julia> StepRangeLen{Float32, Base.TwicePrecision{Float32}, Base.TwicePrecision{Float32}}(r)
2.0f0:1.0f0:3.0f0

? Not much better than your solution though

julia> 2.0f0:1.0f0:3.0f0
2.0f0:1.0f0:3.0f0

?

There’s a decent argument Float32.(r) should just return a range. I’m not sure how breaking this would be in practice.

1 Like

think about what map(identity, r) should do and then if identity.(r) should return the same result. If these two should both (semantically) give you collect(r), then Float32.(r) shouldn’t return a range IMO.

Here’s what map does:

julia> map(Float32, r)
2.0f0:1.0f0:3.0f0

julia> map(identity, r)
2-element Vector{Float64}:
 2.0
 3.0

julia> map(Int, r)
2-element Vector{Int64}:
 2
 3
1 Like

map(Float32, r) appears to be exactly what I wanted for this problem. map seems to have special methods for converting the eltype of ranges by calling appropriate constructors. This is perhaps not a general solution though.