lottery.php 概率计算代码 $v){ $rand_num_max += $v['rate']; } // 初始化随机数,奖品区间 $rand_num = mt_rand(1, $rand_num_max); $left_interval = 0; $right_interval = 0; $last_right_interval = 0; foreach($arr_prize as $k = $v)
概率计算代码 $v){ $rand_num_max += $v['rate']; } // 初始化随机数,奖品区间 $rand_num = mt_rand(1, $rand_num_max); $left_interval = 0; $right_interval = 0; $last_right_interval = 0; foreach($arr_prize as $k => $v){ // 左区间 $left_interval = $last_right_interval; // 右区间 $right_interval = $left_interval + $v['rate']; // 上一个右区间 $last_right_interval = $right_interval; // 判断随机数是否落在对应的区间 if($left_interval < $rand_num && $rand_num <= $right_interval){ return $k; } } } // 总概率精度是100,这样比较好计算概率是否正常 $arr_prize = array( array('id' => 1, 'name' => '一等奖', 'rate' => 1), array('id' => 2, 'name' => '二等奖', 'rate' => 5), array('id' => 3, 'name' => '三等奖', 'rate' => 10), array('id' => 4, 'name' => '四等奖', 'rate' => 12), array('id' => 5, 'name' => '五等奖', 'rate' => 22), array('id' => 6, 'name' => '不中奖', 'rate' => 50), ); // 中奖概率测试 $bingo_test = array(0,0,0,0,0,0); $lottery_count = 10000; $i = 0; while($i++ < $lottery_count){ $bingo_index = _get_bingo_index($arr_prize); $bingo_test[$bingo_index]++; } foreach($bingo_test as $k => $v){ echo $arr_prize[$k]['name'] , '中奖几率:' , ($v / $lottery_count) * 100 , '%'; } ?>