PHP获取固定概率

public static  function getFixRand($weight) {
        if ((int)$weight < 0 || (int)$weight > 100) {
            return -1;
        }

        $weightArr = [
            1 => $weight,
            2 => 100-$weight,
        ];

        $result = '';

        //概率数组的总概率精度
        $sumWeight = array_sum($weightArr); //计算数组中元素的和
        $luckyNum = mt_rand(1, $sumWeight);
        //概率数组循环
        $beginCursor = $endCursor = 0;
        foreach ($weightArr as $id => $w) {
            $beginCursor = $endCursor;
            $endCursor += $w;

            if ($luckyNum > $beginCursor && $luckyNum <= $endCursor) {
                $result = $id;
                break;
            }
        }
        if ($result == 1) {
            return true;
        } else {
            return false;
        }
    }

posted @ 2019-01-21 21:34  TBHacker  阅读(339)  评论(0编辑  收藏  举报