php 使用加权概率生成随机数[重复]

46qrfjad  于 2023-05-21  发布在  PHP
关注(0)|答案(3)|浏览(117)

此问题已在此处有答案

Generating random results by weight in PHP?(13个回答)
9年前关闭。
我想从一组数字中随机选择一个数字,但要基于概率;例如(2-6)。
我想要以下分发:

  • 6的概率应该是10%
  • 5的概率应该是40%
  • 4的概率应该是35%
  • 3的概率应该是5%
  • 2的概率应该是5%
iyr7buue

iyr7buue1#

这很容易做到。注意下面代码中的注解。

$priorities = array(
    6=> 10,
    5=> 40,
    4=> 35,
    3=> 5,
    2=> 5
);

# you put each of the values N times, based on N being the probability
# each occurrence of the number in the array is a chance it will get picked up
# same is with lotteries
$numbers = array();
foreach($priorities as $k=>$v){
    for($i=0; $i<$v; $i++)  
        $numbers[] = $k;
}

# then you just pick a random value from the array
# the more occurrences, the more chances, and the occurrences are based on "priority"
$entry = $numbers[array_rand($numbers)];
echo "x: ".$entry;
iyfjxgzm

iyfjxgzm2#

创建一个介于1和100之间的数字。

If      it's <= 10       -> 6
Else if it's <= 10+40    -> 5
Else if it's <= 10+40+35 -> 4

等等...
注意:你的概率加起来不是100%。

qcuzuvrc

qcuzuvrc3#

最好的方法是生成一个0到100之间的数字,然后看看这个数字在什么范围内:

$num = rand(0, 100);
if ($num < 10) {
    $result = 6;    
} elseif ($num < 50) { // 10 + 40
    $result = 5;
} elseif ($num < 85) { // 10 + 40 + 35
    $result = 4;
} elseif ($num < 90) { // 10 + 40 + 35 + 5
    $result = 3;
} else {
    $result = 2;
}

注意,如果你的总概率不等于1,那么有时$result将是未定义的。

相关问题