Generate a sequence of random numbers that sum up to 1?

Alex Martelli aleaxit at yahoo.com
Sat Apr 22 03:27:30 EDT 2006


Anthony Liu <antonyliu2002 at yahoo.com> wrote:
   ...
> As a matter of fact, given that we have to specify the
> number of states for an HMM, I would like to create a
> specified number of random floating numbers whose sum
> is 1.0.

def forAL(N):
     N_randoms = [random.random() for x in xrange(N)]
     total = sum(N_randoms)
     return [x/total for x in N_randoms]


Does this do what you want?  Of course, the resulting numbers are not
independent, but then the constraints you pose would contradict that.


Alex



More information about the Python-list mailing list