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

Gerard Flanagan grflanagan at yahoo.co.uk
Sun Apr 23 10:29:36 EDT 2006


Nick Craig-Wood wrote:
> Gerard Flanagan <grflanagan at yahoo.co.uk> wrote:
> >  def distribution(N=2):
> >      p = [0] + sorted( random.random() for _ in range(N-1) ) + [1]
> >      for j in range(N):
> >          yield p[j+1] - p[j]
> >
> >  spread = list(distribution(10))
> >
> >  print spread
> >  print sum(spread)
>
> This is simpler, easier to prove correct and most likely quicker.
>
> def distribution(N=2):
>     L = [ random.uniform(0,1) for _ in xrange(N) ]
>     sumL = sum(L)
>     return [ l/sumL for l in L ]
>

simpler:- ok

easier to prove correct:- in what sense?

quicker:- slightly slower in fact (using xrange in both functions).
This must be due to 'uniform' - using random() rather than uniform(0,1)
then yes, it's quicker. Roughly tested, I get yours (and Alex
Martelli's) to be about twice as fast. (2<=N<1000, probably greater
difference as N increases).

All the best.

Gerard




More information about the Python-list mailing list