How can I add random numbers (for example from 1 to 100) into an array using Julia language? Also, the array already has to have a defined length (for example 30 numbers).
CodePudding user response:
If your initial vector is v
, you can do as follows:
v . = rand(1:100,length(v))
rand(1:100,length(v))
will generate a random vector of integers between 1 and 100 and of length identical tov
's one (thelength(v)
part), you can read the rand() doc for further details.. =
is the Julia syntax to do an "in-place" vector addition. Concerning performance, this is an important syntax to know, see "dot call" syntax
Update a more efficient approach, is :
map!(vi->vi rand(1:100),v,v)
Note: the approach is more efficient as it avoids the creation of the rand(1:100,length(v))
temporary vector.
Update a more elegant and efficient approach, is @DNS's one (see comment) :
using Random
rand!(v,1:100)
Note: the approach is efficient, as it also avoids the creation of a temporary vector by using a for loop to modify components. The function code is:
rand!(A::AbstractArray{T}, X) where {T} = rand!(default_rng(), A, X)
# ...
function rand!(rng::AbstractRNG, A::AbstractArray{T}, sp::Sampler) where T
for i in eachindex(A)
@inbounds A[i] = rand(rng, sp)
end
A
end
CodePudding user response:
the idiomatic way of doing this in one line is probably
julia> v = zeros(3)
julia> v . = rand.((1:100, ))
3-element Vector{Float64}:
35.0
27.0
89.0
julia> @benchmark x . = rand.((1:100, )) setup=(x = zeros(100))
BenchmarkTools.Trial: 10000 samples with 241 evaluations.
Range (min … max): 313.544 ns … 609.581 ns ┊ GC (min … max): 0.00% … 0.00%
Time (median): 323.021 ns ┊ GC (median): 0.00%
Time (mean ± σ): 327.143 ns ± 20.920 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▃▇██▇▆▆▅▄▃▂▂▁▁▁▁▁ ▁ ▂
██████████████████████████▇▇▆▆▆▅▆▆▆▅▅▅▅▁▅▄▃▅▁▁▁▃▃▁▁▁▃▄▃▃▁▁▁▁▃ █
314 ns Histogram: log(frequency) by time 415 ns <
Memory estimate: 0 bytes, allocs estimate: 0.
as you can see, this version is allocation-free thanks to broadcast loop fusion