Julia Equivalent of Python Numpy "Arange"

Julia Equivalent of Python Numpy "Arange"

In Python, I can create an array of evenly spaced values using

xi2 = np.arange(0, np.sqrt(6), 1e-3)

How do I write this in Julia? I tried,

xi2 = range(0,sqrt(6),step=1e-3)

but this returns 0.0:0.001:2.449

1 Answer

The result, 0.0:0.001:2.449 is indeed a range of evenly spaced values, and can be indexed, sliced, broadcasted on, and generally used just like any other AbstractArray. For example:

julia> xi2 = range(0,sqrt(6),step=1e-3)
0.0:0.001:2.449

julia> xi2[1]
0.0

julia> xi2[100]
0.099

julia> length(xi2)
2450

julia> isa(xi2, AbstractArray)
true

julia> sin.(xi2)
2450-element Vector{Float64}:
 0.0
 0.0009999998333333417
 0.0019999986666669333
 0.002999995500002025
 ⋮
 0.6408405168240852
 0.6400725224915994
 0.6393038880866445
 0.6385346143778549

If for any reason you want to turn xi2 into a full Array preemptively, you can do that with collect

julia> collect(xi2)
2450-element Vector{Float64}:
 0.0
 0.001
 0.002
 0.003
 ⋮
 2.446
 2.447
 2.448
 2.449

which will "materialize" the range, so to speak. This uses a lot more memory than the Range though, and is less often necessary than you might expect.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.