Generating N numbers that sum to 1

Yuval Adam picture Yuval Adam · Jan 31, 2010 · Viewed 10.4k times · Source

Given an array of size n I want to generate random probabilities for each index such that Sigma(a[0]..a[n-1])=1

One possible result might be:

0     1     2     3     4
0.15  0.2   0.18  0.22  0.25

Another perfectly legal result can be:

0     1     2     3     4
0.01  0.01  0.96  0.01  0.01

How can I generate these easily and quickly? Answers in any language are fine, Java preferred.

Answer

Kobi picture Kobi · Jan 31, 2010

Get n random numbers, calculate their sum and normalize the sum to 1 by dividing each number with the sum.