为什么概率结果的方差足够大?
测试代码:
function probability($chances) {
asort($chances);
$sum = array_sum($chances);
$random = mt_rand(1, $sum);
foreach($chances as $key => $chance) {
if($random < $chance)
return $key;
}
return $key;
}
$chances['case1'] = 10;
$chances['case2'] = 30;
$chances['case3'] = 60;
$result = array();
for($i = 0; $i < 100000; $i++)
@$result[probability($chances)]++;
asort($result);
$sum = array_sum($result);
echo "Case\tCount\tOrig\tResult\n";
foreach($result as $key => $value)
echo "$key\t$value\t".$chances[$key]."%\t".round($value / $sum * 100)."%\n";
结果:
Case Count Orig Result
case1 14913 10% 15%
case2 33099 30% 33%
Case3 51988 60% 52%
有没有可能以某种方式调整它?我试图使用mt_srand()
,但它没有帮助。
信息:
$ php -v
PHP 5.3.10-1ubuntu3.2 with Suhosin-Patch (cli) (built: Jun 13 2012 17:20:55)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
with Suhosin v0.9.33, Copyright (c) 2007-2012, by SektionEins GmbH
$ uname -a
Linux desktop 3.2.0-26-generic-pae #41-Ubuntu SMP Thu Jun 14 16:45:14 UTC 2012 i686 i686 i386 GNU/Linux