So I am trying to make a script that will randomly split a value of 4 into 12 different variables. I can't think of a good way to do this properly. I thought about randomizing numbers so that they are close to 0.33 (1/12 of 4) but that would often lead to the last few numbers being underprioritized. Anyone tried anything like this before or have any great ideas for how to make this as random and evenly uneven as possible?
3 Answers
Generate 12 random numbers from your favourite random number generator, call them r1..r12
.
Add them all up, call the sum sum
.
Your first random fraction of 4
is (r1/sum)*4
. The rest should be obvious.

- 77,191
- 7
- 105
- 161
-
1Note that this solution does not generate sets of numbers that are uniformly distributed in the logical way, but it IS the solution that most people seem to choose because they do not understand why it fails to produce something truly uniform. – Feb 19 '13 at 16:09
-
1@woodchips: it would have been helpful to provide some substantiation for this criticism (although it's correct), and even more helpful to provide an answer which does generate uniformly distributed partitions. I've tried to do the latter, although I'm not sure that it's correct either. – rici Feb 19 '13 at 19:21
-
2@rici - I COULD do that, but it would take a long answer, not something that would fit into a comment. And anyway, I've ALREADY done that in EXTREME detail. Really, this question should arguably be closed as a duplicate. http://stackoverflow.com/questions/8064629/random-numbers-that-add-to-100-matlab/8068956#8068956 – Feb 19 '13 at 21:17
-
2@woodchips, thanks, that link is useful. Theoretically, this question differs from the linked question because this question is over a continuous domain, while the linked question is discrete. Of course, in practice, both of them are discrete, but the answer will depend on whether the continuous solution is sufficiently good an approximation. – rici Feb 19 '13 at 23:25
Generate any random number greater than 1 and after rescale to required sum.
Example:
- Required sum: 4
- Random Numbers: 1 2 3 4 5 6 7 8 9 10 11 12
- Sum = 78
- Rescaled numbers:
1 rescaled to (1*4) / 78
2 rescaled to (2*4) / 78
...
12 rescaled to (12*4) / 78

- 2,839
- 15
- 23
The following algorithm provides uniformly distributed partitions, assuming that it is possible to generate uniformly distributed random numbers over a continuous range (or, at least, over a discrete range with sufficiently many possible values that the odds of duplication are negligible).
To produce a partition of t
into k
values:
Generate
k-1
uniformly distributed values in the range[0, t]
.Sort them, and add
0
at the beginning andt
at the end.Use the adjacent differences as the partition.

- 234,347
- 28
- 237
- 341