random numbers according to user defined distribution ??

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Aug 6 21:26:54 EDT 2008


On Wed, 06 Aug 2008 15:02:37 -0700, Alex wrote:

> Hi everybody,
> 
> 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 :-(


This is a strange question. Of course you can -- just write a function to 
do so! Here's some easy ones to get you started:

from __future__ import division
import random, maths

def unbounded_rand(p=0.5):
    """Return a random integer between 0 and infinity."""
    if not (0 < p <= 1):
        raise ValueError
    n = 0
    while random.random() < p:
        n += 1
    return n

def pseudonorm():
    """Return a random float with a pseudo-normal distribution.

    The probability distribution is centered at 0 and bounded 
    by -1 and +1.
    """
    return (sum([random.random() for i in range(6)])-3)/3

def triangular(min=0, max=1, mode=0.5):
    """Return a random float in the range (min, max) inclusive
    with a triangular histogram, and the peak at mode.
    """
    u = random.random()
    if u <= (mode-min)/(max-min):
        return min + math.sqrt(u*(max-min)*(mode-min))
    else:
        return max - math.sqrt((1-u)*(max-min)*(max-mode))

def linear():
    """Return a random float with probability density 
    function pdf(x)=2x.
    """
    return math.sqrt(random.random())



There's no general way to create a random function for an arbitrary 
distribution. I don't think there's a general way to *describe* an 
arbitrary random distribution. However, there are some mathematical 
techniques you can use to generate many different distributions. Google 
on "transformation method" and "rejection method".

If you have a specific distribution you are interested in, and you need 
some help, please ask.



-- 
Steven



More information about the Python-list mailing list