Generate random numbers with weighted probabilites [duplicate]

感情迁移 提交于 2021-02-08 12:10:36

问题


I want to select a number randomly, but based on probability from a group of numbers; for example (2-6).

I'd like the following distribution:

  • 6's probability should be 10%
  • 5's probability should be 40%
  • 4's probability should be 35%
  • 3's probability should be 5%
  • 2's probability should be 5%

回答1:


The best you can do is generate a number between 0 and 100, and see in what range the number is:

$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;

Be careful, your total probability isn't equal to 1, so sometimes $result is undefined

See @grigore-turbodisel 's answer if you want something that you can configure easily.




回答2:


This is very easy to do. Watch for the comments in the code below.

$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;



回答3:


Create a number between 1 and 100.

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

And so on...

Note: your probabilities don't add up to 100%.



来源:https://stackoverflow.com/questions/17614638/generate-random-numbers-with-weighted-probabilites

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!