Generating random results by weight in PHP?

前端 未结 12 726
青春惊慌失措
青春惊慌失措 2020-11-22 07:35

I know how to generate a random number in PHP but lets say I want a random number between 1-10 but I want more 3,4,5\'s then 8,9,10\'s. How is this possible? I would post wh

12条回答
  •  难免孤独
    2020-11-22 08:13

    For an efficient random number skewed consistently towards one end of the scale:

    • Choose a continuous random number between 0..1
    • Raise to a power γ, to bias it. 1 is unweighted, lower gives more of the higher numbers and vice versa
    • Scale to desired range and round to integer

    eg. in PHP (untested):

    function weightedrand($min, $max, $gamma) {
        $offset= $max-$min+1;
        return floor($min+pow(lcg_value(), $gamma)*$offset);
    }
    echo(weightedrand(1, 10, 1.5));
    

提交回复
热议问题