mt_rand - php 隨機函數 實際機率和設定的機率有差異

來源:互聯網
上載者:User
php 0.1,    5 => 1,    1 => 27,    2 => 27,    3 => 27,    4 => 17.9,);$nums = 30000000;for($i=1;$i<$nums;$i++){    //srand((double)microtime(true)*1000000);    srand((double)microtime(true)*1000000);    $random =  mt_rand(1, 1000000);    $rand = 0;    $thisID = 0;    foreach($configSet as $k => $value){        $rand += $value * 10000;        if($random <= $rand){            $thisID = $k;            break;        }    }    $result[$thisID] += 1;}foreach($result as $key => $value){    $result[$key] = round((float)($value / $nums) * 1000000)/10000;}ksort($result);print_r($result);?>

結果是

Array(    [1] => 26.985    [2] => 26.9879    [3] => 26.987    [4] => 17.9519    [5] => 0.9917    [6] => 0.0964)

跑了很多次都是差不多的,
實際使用者10000W次結果就有點問題

Array(    [1] => 27.0581    [2] => 27.2639    [3] => 27.2125    [4] => 18.1036    [5] => 0.3031    [6] => 0.0588)

怎麼能保證小機率的時候波動小一點

回複內容:

php 0.1,    5 => 1,    1 => 27,    2 => 27,    3 => 27,    4 => 17.9,);$nums = 30000000;for($i=1;$i<$nums;$i++){    //srand((double)microtime(true)*1000000);    srand((double)microtime(true)*1000000);    $random =  mt_rand(1, 1000000);    $rand = 0;    $thisID = 0;    foreach($configSet as $k => $value){        $rand += $value * 10000;        if($random <= $rand){            $thisID = $k;            break;        }    }    $result[$thisID] += 1;}foreach($result as $key => $value){    $result[$key] = round((float)($value / $nums) * 1000000)/10000;}ksort($result);print_r($result);?>

結果是

Array(    [1] => 26.985    [2] => 26.9879    [3] => 26.987    [4] => 17.9519    [5] => 0.9917    [6] => 0.0964)

跑了很多次都是差不多的,
實際使用者10000W次結果就有點問題

Array(    [1] => 27.0581    [2] => 27.2639    [3] => 27.2125    [4] => 18.1036    [5] => 0.3031    [6] => 0.0588)

怎麼能保證小機率的時候波動小一點

把srand放到迴圈外

實際機率和設置機率有差異。。。

你怎麼知道實際機率是多少的?

你知道的只是頻率好不好。。。

你的問題本身就是錯的。

而頻率和機率不等幾乎是必然的。。。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.