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?
To "divide evenly" means that one number can be divided by another without anything left over. In other words no remainder! But 7 cannot be evenly divided by 2, as there will be one left over.
Use the math. modf() method to split a number into integer and decimal parts, e.g. result = math.
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.
Generate any random number greater than 1 and after rescale to required sum.
Example:
1 rescaled to (1*4) / 78
2 rescaled to (2*4) / 78
...
12 rescaled to (12*4) / 78
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 and t
at the end.
Use the adjacent differences as the partition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With