random numbers according to user defined distribution ??

Robert Kern robert.kern at gmail.com
Fri Aug 8 10:32:03 CEST 2008

sturlamolden wrote:
> 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.

I don't know. I think the certainty that rejection sampling actually gives you 
the desired distribution as opposed to MH's uncertainty is very much a 
worthwhile tradeoff for univariate distributions. Sure, you throw away fewer 
samples, but you know that MH isn't throwing away samples that it ought to. 
Personally, I view MH as a last resort when the dimensionality gets too large to 
do anything else. But then, that's just my opinion.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-list mailing list