Generate a sequence of random numbers that sum up to 1?
Edward Elliott
nobody at 127.0.0.1
Fri Apr 21 23:16:07 EDT 2006
Anthony Liu wrote:
> But, I want the random numbers just generated sum up
> to 1 .
This seems like an odd request. Might I ask what it's for?
Generating random numbers in [0,1) that are both uniform and sum to 1 looks
like an unsatisfiable task. Each number you generate restricts the
possibilities for future numbers. E.g. if the first number is 0.5, all
future numbers must be < 0.5 (indeed, must *sum* to 0.5). You'll end up
with a distribution increasingly skewed towards smaller numbers the more
you generate. I can't imagine what that would be useful for.
If that's not a problem, do this: generate the numbers, add them up, and
divide each by the sum.
nums = [random.uniform(0,1) for x in range(0,100)]
sum = reduce(lambda x,y: x+y, nums)
norm = [x/sum for x in nums]
Of course now the numbers aren't uniform over [0,1) anymore.
Also note that the sum of the normalized numbers will be very close to 1,
but slightly off due to representation issues. If that level of accuracy
matters, you might consider generating your rands as integers and then
fp-dividing by the sum (or just store them as integers/fractions).
More information about the Python-list
mailing list