How to sample from a truncated distribution without allocating too much memory

Some small and one big thing:

Don’t use collect, and use a UnitRange instead of a StepRange, so 0:d instead of collect(0:1:d).

Prefer 1:N and 1:20. These don’t matter for allocations, and probably very little or nothing for speed.

This one is big:

Any call like rand(distr, 1)[1] allocates and populates an array and then reads out its first element. That’s bad. Instead, create a random scalar:

rand(distr) 

Also, your rounding is not good. It creates an integer valued float which is then converted when assigned to prop_draw. Instead, round directly to the correct type:

round(Int8, x) 

So try

prop_draw[i] = round(Int8, rand(Distr_sample[draw[i]+1])) 
3 Likes