简体   繁体   English

PHP 中的加权随机选择

[英]Weighted Random Choice In PHP

I need help getting a my probability odds closer to testing results with low percentages.我需要帮助以使我的概率赔率更接近低百分比的测试结果。 What I have seems to work for percentages at 1% or higher but I need it to work with very low percentages such as 0.02% (down to 4 decimals).我所拥有的似乎适用于 1% 或更高的百分比,但我需要它以非常低的百分比工作,例如 0.02%(低至小数点后 4 位)。 Anything below 1% tends to end up having around a 1% probability after running tests from running 1000-100000 tests at once the results are similar.在运行 1000-100000 次测试后,任何低于 1% 的结果往往最终有大约 1% 的概率,结果相似。

Example Results示例结果

ID  Odds    Test Total  Test Odds
1   60.0000 301773  60.3546%
2   30.0000 148360  29.672%
3   9.9800  44897   8.9794%
4   0.0200  4970    0.994%

Function Function

// $values = [1,2,3,4]
// $weights = [60.0000,30.0000,9.9800,.0200]
private function getRandom($values, $weights)
{
    $count = count($values); 
    $i = 0; 
    $n = 0; 
    $num = mt_rand(0, array_sum($weights)); 
    while($i < $count)
    {
        $n += $weights[$i]; 
        if($n >= $num)
            break; 
        $i++; 
    } 
    return $values[$i]; 
}

mt_rand returns an integer so comparing it to 0.02 is effectively the same as comparing it to 1. Hence you always get around 1% for the weights which are less than 1%. mt_rand返回一个 integer,因此将其与 0.02 进行比较实际上与将其与 1 进行比较相同。因此,对于小于 1% 的权重,您总是得到大约 1%。 Try computing $num like this instead:尝试像这样计算$num

$num = mt_rand(0, array_sum($weights) * 100) / 100; 

Demo on 3v4l.org 3v4l.org 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM