random numbers according to user defined distribution ??

sturlamolden sturlamolden at yahoo.no
Fri Aug 8 06:40:20 CEST 2008


Alex wrote:

> I wonder if it is possible in python to produce random numbers
> according to a user defined distribution?
> Unfortunately the random module does not contain the distribution I
> need :-(

There exist some very general algorithms to generate random numbers
from arbitrary distributions.

The most notable of these are "Markov Chain Monte Carlo", e.g. the
Metropolis-Hastings algorithm. It is very easy to implement in any
programming language. The nature MCMC algorithms makes it inefficient
when implemented in pure Python. But you can get tremendous speedup by
simulating multiple Markov chains in parallel, by means of vectorizing
with NumPy.

A relative of Metropolis-Hastings which may also be applicable to your
problem is pure "rejection sampling". It is far less efficient, but
produces no autocorrelation in the samples.

If you can generate random deviates from the marginal distributions,
but need to sample the joint distribution, look into using the Gibbs
sampler. It is an efficient version of Metropolis-Hastings for this
special case.

http://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm
http://en.wikipedia.org/wiki/Rejection_sampling
http://en.wikipedia.org/wiki/Gibbs_sampling




More information about the Python-list mailing list