t as mixture of Normals

(Based on Rasmus Bååth’s post)

A scaled tt distribution, with μ\mu mean, ss scale and ν\nu degrees of freedom, can be simulated

from a mixture of Normals with μ\mu mean and precisions following a Gamma distribution:

 0 

Since I’ve recently pickep up again the crystal-gsl in my spare time, I’ve decided to replicate the previously mentioned post using a Crystal one-liner.

To simulate 10,000 samples from t2(0,3)t_2\left(0,3\right) using the mixture, we can then write:

samples = (0..10000).map { |x|
   Normal.sample 0.0, 1.0/Math.sqrt(Gamma.sample 1.0, 9.0)
}

We can see the mixture distribution (histogram) converging nicely to the (t2(0,3)(t_2(0,3) (red):