|
Description:
Just a few lines of code if you are willing to use numpy. Uses fact that any prob. distr. can be sampled by computing the cumulative distribution, drawing a random number from 0 to 1, and finding the x-value where that number is attained on the cumulative distribution. The searchsorted(..) function performs this search.
Source: Text Source
from numpy import *
from numpy.random import random
def toss(c, sh):
"""Return random samples of cumulative vector (1-D numpy array) c
The samples are placed in an array of shape sh.
Each element of array returned is an integer from 0 through n-1,
where n is the length of c."""
y = random(sh)
x = searchsorted(c,y)
return x
p=array((0.1, 0.2, 0.6, 0.1))
c=cumsum(p)
print toss(c, (10,))
Discussion:
|