Random values with non-uniform distribution

后端 未结 2 1430
长情又很酷
长情又很酷 2021-01-07 13:27

I want a random number generator with non-uniform distribution, ie:

// prints 0 with 0.1 probability, and 1 with 0.9 probability
echo probRandom(array(10, 90         


        
2条回答
  •  迷失自我
    2021-01-07 14:10

    If you know the sum of all elements in $probs, you can do this without preprocessing.

    Like so:

    $max = sum($probs);
    $r = rand(0,$max-1);
    $tot = 0;
    for ($i = 0; $i < length($probs); $i++) {
        $tot += $probs[$i];
        if ($r < $tot) {
            return $i;
        }
    }
    

    This will do what you want in O(N) time, where N is the length of the array. This is a firm lower bound on the algorithmic runtime of such an algorithm, as each element in the input must be considered.

    The probability a given index $i is selected is $probs[$i]/sum($probs), given that the rand function returns independent uniformly distributed integers in the given range.

提交回复
热议问题