Adam Laiacano

I'm a data engineer working here at tumblr, living in Brooklyn, and
Currently listening to: .

2011-12-29 Notes: 12

Python function for sampling from an arbitrary discrete distribution

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:


  1. blogbourse reblogged this from adamlaiacano
  2. adamlaiacano posted this