Sampling is fun, right? Here’s a simple implementation of a slice sampler for discrete probability distributions.
And here’s how to call it:
>>> px=[.2, .4, .1, .3]
>>> slice_sampler(px, N=5)
array([2, 3, 3, 3, 3])
>>> slice_sampler(px, N=5, x=[100, 200, 300, 400])
array([200, 200, 400, 200, 200])
Set N to something high and take a histogram and you’ll see that you have the right distribution.
>>> from pylab import *
>>> samples = slice_sampler(px, N=10000, x=[100, 200, 300, 400])
>>> hist(samples)
>>> grid()
And here’s what you get:
