Stream: helpdesk (published)

Topic: ✔ Convert a range of floats to a range of integers


view this post on Zulip Andreas (Dec 05 2022 at 12:19):

This seems trivial but I haven't found a way to do it. I have range of floating numbers

julia> ts
10000.0:1.0:20000.0

and I would like to convert it to a range of integers to use it to index an array, ie I would like to get 10000:1:20000. The closest I come is with

floor.(Int, ts)

but this returns an array not a range. The array works fine for indexing but I wonder if there is a more julian way of doing this.

view this post on Zulip Jack Shannon (Dec 05 2022 at 12:26):

julia> ts = 1e5:1.0:2e5
100000.0:1.0:200000.0

julia> dump(ts)
StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}
  ref: Base.TwicePrecision{Float64}
    hi: Float64 100000.0
    lo: Float64 0.0
  step: Base.TwicePrecision{Float64}
    hi: Float64 1.0
    lo: Float64 0.0
  len: Int64 100001
  offset: Int64 1

julia> range(Int(ts.ref.hi), step=Int(ts.step.hi), length=ts.len)
100000:1:200000

view this post on Zulip Andreas (Dec 05 2022 at 12:28):

:star_struck: I had no idea that a range was a struct with fields you can access. Thank you :smile:

view this post on Zulip Notification Bot (Dec 05 2022 at 12:28):

Andreas has marked this topic as resolved.

view this post on Zulip Sukera (Dec 05 2022 at 12:41):

the fields are not API, so it's better to write this as

julia> ts = 1e5:1.0:2e5
100000.0:1.0:200000.0

julia> Int(first(ts)):Int(step(ts)):Int(last(ts))
100000:1:200000

view this post on Zulip Andreas (Dec 05 2022 at 12:44):

Makes sense. I should have thought of that

view this post on Zulip Sukera (Dec 05 2022 at 12:53):

crucially, that'll also work with other kinds of ranges, like this one:

julia> ts = 10^5:2*10^5
100000:200000

julia> ts.step
ERROR: type UnitRange has no field step
Stacktrace:
 [1] getproperty(x::UnitRange{Int64}, f::Symbol)
   @ Base ./Base.jl:37
 [2] top-level scope
   @ REPL[5]:1

julia> Int(first(ts)):Int(step(ts)):Int(last(ts))
100000:1:200000

view this post on Zulip Andreas (Dec 05 2022 at 13:14):

Great, thank you :smile:


Last updated: Nov 22 2024 at 04:41 UTC