自己在项目里面用了一下,感觉还不错!!! //红包金额 public function redPacket() { $a = $this->__randomFloat(2,3); $b = $this->__randomFloat(3,5); $c = $this->__randomFloat(5,7); $d = $this->__randomFloat(7,8); //人均2-3块,最低2块,最高8块 $prize_arr = array( '0' => array('id'=>1,'prize'=>$a,'v'=>94), '1' => array('id'=>2,'prize'=>$b,'v'=>3), '2' => array('id'=>3,'prize'=>$c,'v'=>2), '3' => array('id'=>4,'prize'=>$d,'v'=>1), ); foreach ($prize_arr as $key => $val) { $arr[$val['id']] = $val['v']; } $rid = $this->__get_rand($arr); //根据概率获取奖项id $res = $prize_arr[$rid-1]['prize']; //中奖项 return $res; }//概率计算 private 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; } //随机小数 private function __randomFloat($min, $max) { $num = $min + mt_rand() / mt_getrandmax() * ($max - $min); return sprintf("%.2f", $num); }
红包金额概率计算
最新推荐文章于 2023-02-15 17:55:29 发布