I was wondering if there's a quick way to generate a x
number of random percentages that sum up to 100%?
I've tried writing this function, however more times than not the 100% gets used up in the first 2 or 3 iterations and the rest are just 0%, and I'd like to keep all of the percentages above 0.
function randomPercentages($x) {
$percent = 100;
$return = array();
for($i=1; $i <= $x; $i++) {
$temp = mt_rand(1, $percent);
$return[] = $temp;
$percent -= $temp;
}
return $return;
}
print_r(randomPercentages(7));
Step 1: Generate a bunch of floats between 0 and 1. (or 0 and 100 if you wanna work with percentages right away)
Step 2: Sort them.
EDIT: Step 2 1/2: Add 0 and 1 to begin and end of list.
Step 3: Iterate over them. The differences between the current and previous ones are your random percentages.
Example:
0.23, 0.65, 0.77
0.23 - 0.00 = 23%
0.65 - 0.23 = 42%
0.77 - 0.65 = 12%
1.00 - 0.77 = 23%
----
100%
Some untested code:
$num = 5;
$temp = [0.0];
for ($i=0; $i<$num; $i++) $temp[] = mt_rand() / mt_getrandmax();
sort($temp);
$temp[] = 1.0;
$percentages = [];
for ($i=1; $i<count($temp); $i++) $percentages[] = $temp[$i] - $temp[$i-1];
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