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

Gerard Flanagan grflanagan at yahoo.co.uk
Sat Apr 22 04:17:35 EDT 2006


Anthony Liu wrote:
> I am at my wit's end.
>
> I want to generate a certain number of random numbers.
>  This is easy, I can repeatedly do uniform(0, 1) for
> example.
>
> But, I want the random numbers just generated sum up
> to 1 .
>
> I am not sure how to do this.  Any idea?  Thanks.
>

--------------------------------------------------------------
import random

def partition(start=0,stop=1,eps=5):
    d = stop - start
    vals = [ start + d * random.random() for _ in range(2*eps) ]
    vals = [start] + vals + [stop]
    vals.sort()
    return vals

P = partition()

intervals = [ P[i:i+2] for i in range(len(P)-1) ]

deltas = [ x[1] - x[0] for x in intervals ]

print deltas

print sum(deltas)
---------------------------------------------------------------

Gerard




More information about the Python-list mailing list