Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array of probability with fractions

Tags:

php

random

math

i have the following array:

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

// it sums in 100%

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

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

Please let me know what is the function you suggest me to use.

like image 839
Liad Livnat Avatar asked Dec 27 '22 07:12

Liad Livnat


1 Answers

Convert the percentages to an accumulated probability, then compare it with a random number.

If the random number falls into a category, outputs the result. If not, move onto the next one until one is found. This allows you to output a number based on the percentage probability stated 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;
    }
}
like image 191
Antony Avatar answered Jan 09 '23 12:01

Antony