Julia: Sample from a custom distribution and perform an in-place update

Viewed 95

I know how to use randn! to sample from the standard normal distribution and perform an in-place update. For example,

rng = MersenneTwister(1234);
A = zeros(5);
randn!(rng, A)

updates A with five numbers sampled from the standard normal.

However, suppose I used Distributions.jl and created a custom distribution, called dist. I know how to sample from it using rand, but it does not perform an in-place update. If I need to repeatedly sample from dist and store the values in A, I would end up with a huge memory allocation. Is there a function like randn! that allows me to sample from a custom distribution?

2 Answers

This is the way to do it:

julia> using Random, Distributions

julia> dist = Poisson(1.0)
Poisson{Float64}(λ=1.0)

julia> rng = MersenneTwister(1234);

julia> x = rand(rng, dist, 5)
5-element Vector{Int64}:
 0
 0
 1
 0
 0

julia> rand!(rng, dist, x)
5-element Vector{Int64}:
 1
 1
 3
 0
 4

note the help of rand!:

rand!(::AbstractRNG, ::Sampleable, ::AbstractArray)

Samples in-place from the sampler and stores the result in the provided array.

In addition to the rand! approach, it is possible to use broadcasting:

A .= rand.(dist)
Related