PHP probability array with fractions

I have the following array:

public $percentage = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 ); 

// it adds up to 100%

I need a random function to return the key a percentage of the value,

for example: the ability to get 0 is 20.30%, and the ability to get 2 is 14.15%, the first user got 0, the second got 2.

Please let me know what feature you are offering me to use.

+4
source share
4 answers

Convert interest to cumulative probability, then compare them with a random number.

If a random number falls into the category, displays the result. If not, go to the next until you find it. This allows you to derive a number based on the percentage probability specified in the array.

 $percentage = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 ); $random = mt_rand(0,10000)/100; foreach ($percentage as $key => $value) { $accumulate += $value; if ($random <= $accumulate) { echo $key; break; } } 
+7
source
 $random_n = mt_rand(0,10000)/100; while(true){ if($random_n <= $percentage[0]) echo 0; break; else if($random_n <= $percentage[1]) echo 1; break; else if($random_n <= $percentage[2]) echo 2; break; else if($random_n <= $percentage[3]) echo 3; break; else $random_n = mt_rand(0,10000)/100; //generate a new random # } 
+2
source
 <?php $percentage = $tmp = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 ); sort($tmp); $rand = mt_rand(0,100); foreach($tmp as $percent) { if($percent >= $rand) { echo array_search($percent,$percentage); die(); } } echo (count($percentage) - 1); 
+1
source

I would do something like:

  • Take a random number from 1 to 10,000 (because you have four significant digits)
  • If the number is between 1 and 2030, then it is zero, if it is between 2031 and (2031 + 1996), then it is 1, etc.
  • ...
  • Profit
0
source

All Articles