I want to get N random numbers that the sum of them is a value.
For example, let's suppose I want 5 random numbers that their sum is 1
Then, a valid possibility is:
0.2 0.2 0.2 0.2 0.2
Other possibility is:
0.8 0.1 0.03 0.03 0.04
And so on. I need this for the creation of the matrix of belongings of the Fuzzy C-means.
Short Answer:
Longer Answer:
The above solution does not yield an uniform distribution which might be an issue depending on what these random numbers are used for. Another method proposed by Matti Virkkunen:
I'm not sure if this yield an uniform distribution
Expanding on Guillaume's accepted answer, here's a Java function that does exactly that.
In a test run,
getRandDistArray(5, 1.0)
returned the following:You now have N random numbers, and their sum is the desired sum.
You're a little slim on constraints. Lots and lots of procedures will work.
For example, are numbers normally distributed? Uniform?
I'l assume that all the numbers must be positive and uniformly distributed around the mean, M/N.
Try this.
This problem is equivalent to the problem of generating random numbers with a Dirichlet distribution. To generate N positive numbers that sum to a positive number M, where each possible combination is equally likely:
Generate N exponentially-distributed random numbers. One way to generate such a number can be written as—
where
ln(x)
is the natural logarithm ofx
andRNDU()
is a method that returns a random number 0 or greater and less than 1 (e.g., JavaScript'sMath.random()
). Note that generating those numbers with a uniform distribution is not ideal because a biased distribution of random number combinations will result.The result is N numbers in a Dirichlet distribution whose sum is approximately equal to M (I say "approximately" because of rounding error).
This problem is also equivalent to the problem of generating random numbers uniformly from an N-dimensional simplex.
Generate N-1 random numbers between 0 and 1, add the numbers 0 and 1 themselves to the list, sort them, and take the differences of adjacent numbers.