mardi 12 mai 2020

PHP: Weighted probability function, returns incorrect results

I have 2 arrays, one is the Prize Array and other is the Prize Winning Percentage/Weights Array.

Prize Array: Prize 1, Prize 2, Prize 3, Prize 4, Prize 5
Prize Winning Percentage/Weights Array: 5, 5, 5, 70, 15

i.e.

  • Prize 1 has 5% winning chance
  • Prize 2 has 5% winning chance
  • Prize 3 has 5% winning chance
  • Prize 4 has 70% winning chance
  • Prize 5 has 15% winning chance.

Following is my function, which I'm using to calculate the Winning Prize based on it's Winning Percentage/Weight.

<?php
    $values = array(1, 2, 3, 4, 5);
    $weights = array(2, 4, 9, 70, 15);

    $res = weighted_random($values, $weights);
    echo $res; die;

    function weighted_random($values, $weights){ 
        $count = count($values); 
        $i = 0; 
        $n = 0; 
        if (array_sum($weights) <= 0 ) { return $values[$i] . ' - ' . $weights[$i]; }
        $num = mt_rand(1, array_sum($weights)); 
        while($i < $count){
            $n += $weights[$i]; 
            if($n >= $num){
                break; 
            }
            $i++; 
        } 
        return "Number: " . $num . " Value: " . $values[$i] . ' Weight: ' . $weights[$i]; 
    }

?>

Now, this function has run 40 times and out of those 4 times, Prize 2 has been won. If you calculate then 5% of 40 is 2. So the Prize 2 should have been won 2 times, but it didn't.

Is there a problem with the function? Or I'm missing out something?

I have been struggling since long, to find the solution. Please help.




Aucun commentaire:

Enregistrer un commentaire