function get_rand($proArr) {
$result = '';
//概率数组的总概率精度
$proSum = array_sum($proArr);
//概率数组循环
foreach ($proArr as $key => $proCur) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $proCur) {
$result = $key;
break;
} else {
$proSum -= $proCur;
}
}
unset($proArr);
return $result;
}
//测试 100次
$prize_arr = array(1, 15, 34, 50);
$a = $b = $c = $d = 1;
for ($i = 1; $i <= 100; $i++) {
$r = get_rand($prize_arr);
$arr[$i] = $r;
if ($r == 0) {
$a++;
} else if ($r == 1) {
$b++;
} else if ($r == 2) {
$c++;
} else if ($r == 3) {
$d++;
}
}
var_dump($arr);
var_dump($a, $b, $c, $d);
PHP 概率算法
最新推荐文章于 2024-04-30 10:39:33 发布