生成具有不同概率的随机数

时间:2014-04-30 08:07:16

标签: php random

是否可以在PHP中生成随机数,例如1到10,并且让它更可能生成比数字更大的数字?

1 个答案:

答案 0 :(得分:4)

不确定。只是做更多的随机性:

//80% chance that it's going to be a number that's smaller or equal to 5
if (rand(0, 10) <= 8) { 
    $number = rand(0, 5);
} else {
    $number = rand(6, 10);
}

演示代码

<?php

$numbers = array();

for ($i = 0; $i < 1000; $i++) {
    if (rand(0, 10) <= 8) { 
        $number = rand(0, 5);
    } else {
        $number = rand(6, 10);
    }

    $numbers[$number] = (isset($numbers[$number]) ? $numbers[$number] + 1 : 1);
}

print_r($numbers);

<强>输出

Array
(
    [0] => 141
    [1] => 147
    [2] => 135
    [3] => 137
    [4] => 131
    [5] => 148
    [6] => 34
    [7] => 27
    [8] => 36
    [9] => 33
    [10] => 31
)

DEMO