Home > Back-end >  Julia: random multinomial numbers allocation
Julia: random multinomial numbers allocation

Time:10-29

I have to generate a vector of random number drawn from a Multinomial distribution. Since I need to do it inside a loop I would like to reduce the number of allocations. This is my code:

pop = zeros(100)
p = rand(100)
p /= sum(p)

#imagine the next line inside a for loop
@time pop = rand(Multinomial(100, p)) #test1
@time pop .= rand(Multinomial(100, p)) #test2

Why test1 is 2 allocations and test2 is 4? Is there a way of doing it with 0 allocations?

Thanks in advance.

CodePudding user response:

Each sample of a multinomial distribution Multinomial(n, p) is a n-dimensional integer vector that sums to n. So this vector is allocated inside of rand.

I believe you want using rand! which works in-place:

julia> m = Multinomial(100, p);

julia> @time rand!(m, pop);
  0.000010 seconds

Note that I create m object first, as creation of it allocates, so it should be done once.

  • Related