Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 生成带有加权概率的随机数_Php_Algorithm_Random - Fatal编程技术网

Php 生成带有加权概率的随机数

Php 生成带有加权概率的随机数,php,algorithm,random,Php,Algorithm,Random,我想随机选择一个数字,但基于一组数字的概率;例如2-6 我想要以下分发: 6的概率应该是10% 5的概率应该是40% 4的概率应该是35% 3的概率应为5% 2的概率应为5% 创建一个介于1和100之间的数字 If it's <= 10 -> 6 Else if it's <= 10+40 -> 5 Else if it's <= 10+40+35 -> 4 等等 注意:您的概率加起来不是100%。您最好生成一个介于0和100之间

我想随机选择一个数字,但基于一组数字的概率;例如2-6

我想要以下分发:

6的概率应该是10% 5的概率应该是40% 4的概率应该是35% 3的概率应为5% 2的概率应为5%
创建一个介于1和100之间的数字

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


注意:您的概率加起来不是100%。

您最好生成一个介于0和100之间的数字,然后查看该数字的范围:

$num=rand(0,100);

if ($num<10+40+35+5+5) 
    $result=2;

if ($num<10+40+35+5)
    $result=3;

if ($num<10+40+35)
    $result=4;

if ($num<10+40)
    $result=5;

if ($num<10)
    $result=6;
小心,您的总概率不等于1,所以有时$result是未定义的

如果您想要一些可以轻松配置的东西,请参阅@grigore turbodisel的答案。

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


那么它是如何随机的呢?为什么每个人在我提问时都会立即给-ve评分这是随机的,只是不是一个统一的分布,因为你没有展示你做了什么,你的研究是什么,你的问题是什么,这一点都不清楚。我看了一下你之前的问题。一些提示:尝试使用正确的拼写编写在浏览器中安装拼写检查器,编写时使用,正确缩进代码,编写描述性标题,阅读指南。如果你的Q开头不好,那是因为你之前的一些或所有提示都失败了。
$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;