Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading