[SciPy-user] Generate random samples from a non-standard distribution

David M. Cooke cookedm@physics.mcmaster...
Sat Oct 20 12:35:55 CDT 2007

"Manu Hack" <manuhack@gmail.com> writes:

> Hi,
> I've been goolging around but not sure how to generate random samples
> given the density function of a random variable.  I was looking around
> something like scipy.stats.rv_continuous but couldn't find anything
> useful.
> Also, if one wants to do Markov Chain Monte Carlo, is scipy possible
> and if not, what should be a workaround (if still want to do in
> Python).  I heard something like openbugs but seems that debian
> doesn't have a package.

Look at scipy.sandbox.montecarlo (you'll have to add a line with
'montecarlo' on it to scipy/sandbox/enabled_packages.txt to compile it,
and copy some files from numpy/random first).

For instance, scipy.sandbox.montecarlo.intsampler takes a list or array
of weights, and can sample from those. Here's a clip from the docstring:

>>> table = [10, 15, 20]
#representing this pmf:
#x       0       1       2
#p(x)    10/45   15/45   20/45
#The output will be something like:
>>> sampler = intsampler(table)
>>> sampler.sample(10)
array([c, b, b, b, b, b, c, b, b, b], dtype=object)

I use it by sampling from my PDF on a grid, and using those points as
the PMF.

|David M. Cooke              http://arbutus.physics.mcmaster.ca/dmc/

More information about the SciPy-user mailing list