Sampler for arbitrary univariate distribution?

Do we have a sampler for arbitrary univariate distributions implemented somewhere (Ziggurat algorithm or so)?

Not that I am aware of.

If you have the inverse CDF available, you can just draw a uniform z \sim [0,1] with rand, and use F^{-1}(z).

If you only have the CDF, or it is significantly (10–20x times) cheaper than the inverse CDF, you can use a rootfinder to invert it,

I found AdaptiveRejectionSampling.jl, which works fine for my use case - my PDF is actually log-concave, so not fully arbitrary.

1 Like

Would be nice to have something like this at some point:

1 Like

Thanks for the pointer to this very neat paper — it is a nice algorithm, and has a lot of instructive numerical tricks. Implementing something like this in Julia could make a perfect GSOC project for an interested student.

1 Like

I agree, that would make for a nice student project. And we should already have all the infrastructure in place to do the necessary analysis (derivate, etc.) on the PDF automatically.

1 Like

You can use the ApproxFun package. It implements the inverse cdf method but with a powerful approximation of the inverse cdf.

julia> using ApproxFun

julia> f = Fun(x -> exp(-x .^ 2 ./ 2), Interval(1.0, 5.0));
       nsims = 10
10

julia> sample(f, nsims)
10-element Vector{Float64}:
 1.336082989485405
 1.607069776542474
 1.3183351647553678
 1.2442608801899127
 1.9691499351124122
 1.9865874975396451
 1.3504069890433499
 1.2596452654971557
 2.274739748928468
 1.463090656181052
2 Likes

Thanks!

This sample function does not seem to be documented in ApproxFun package documentation. How did you find about it?