Generate a sequence of random numbers that sum up to 1?
Gerard Flanagan
grflanagan at yahoo.co.uk
Sat Apr 22 04:48:20 EDT 2006
Gerard Flanagan wrote:
> 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)
> ---------------------------------------------------------------
>
def partition(N=5):
vals = sorted( random.random() for _ in range(2*N) )
vals = [0] + vals + [1]
for j in range(2*N+1):
yield vals[j:j+2]
deltas = [ x[1]-x[0] for x in partition() ]
print deltas
print sum(deltas)
>>>
[0.10271966686994982, 0.13826576491042208, 0.064146913555132801,
0.11906452454467387, 0.10501198456091299, 0.011732423830768779,
0.11785369256442912, 0.065927165520102249, 0.098351305878176198,
0.077786747076205365, 0.099139810689226726]
1.0
More information about the Python-list
mailing list