Samo Grca
Samo Grca

Reputation: 49

Julia - Random Array

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).

Upvotes: 2

Views: 3330

Answers (2)

Picaud Vincent
Picaud Vincent

Reputation: 10982

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 to v's one (the length(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 an alternative, if you want to fill (and not to add) the vector with random integers, is @DNS's one (see comment) :

using Random

v = Vector{Int}(undef,30)
rand!(v,1:100)

Note:

  • Vector{Int}(undef,30) is the Julia's way to create a vector of 30 uninitialized integers.
  • the rand!()function fills this vector with random integers. Internally it uses a for loop.

.

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

Upvotes: 5

jling
jling

Reputation: 2301

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

Upvotes: 2

Related Questions