[SciPy-user] multinomial-like randint

daishi@egcrc.net daishi at egcrc.net
Mon Jan 23 18:26:06 CST 2006


i'm wondering if i'm missing a function
which does something along the lines of
the following:

import scipy

def randomint(f):
     """Sample from [0, len(f)-1] according to f,
     which doesn't have to be normalized.
     n = len(f)
     s = scipy.sum(f)
     if n == 0 or s == 0.0:
         raise ValueError('Input to randomint must be nonzero')
     r = scipy.random.random()
     for i in xrange(n):
         x = f[i]/s
         if r < x:
             return i
         r -= x
     raise RuntimeError('Error in randomint, fell off of end')

i've found scipy.random.randint which is uniform,
and scipy.random.multinomial, which returns
multi-sample counts which i don't need.
i realize the above is pretty simple, but i
imagine that this must be a relatively common
need, and i'd rather not loop in python, so
i feel like i must not be looking in the right


More information about the SciPy-user mailing list