number generator
Nick Craig-Wood
nick at craig-wood.com
Mon Mar 12 12:30:04 CET 2007
Paul Rubin <http> wrote:
> The fencepost method still seems to be simplest:
>
> t = sorted(random.sample(xrange(1,50), 4))
> print [(j-i) for i,j in zip([0]+t, t+[50])]
Mmm, nice.
Here is another effort which is easier to reason about the
distribution produced but not as efficient.
def real(N, M):
while 1:
t = [ random.random() for i in range(N) ]
factor = M / sum(t)
t = [ int(round(x * factor)) for x in t]
if sum(t) == M:
break
print "again"
assert len(t) == N
assert sum(t) == M
return t
It goes round the while loop on average 0.5 times.
If 0 isn't required then just test for it and go around the loop again
if found. That of course skews the distribution in difficult to
calculate ways!
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list