在PHP范围内生成随机浮点数

在PHP范围内生成随机浮点数,php,random,Php,Random,我有一个通过以下代码初始化骰子对象的代码: public function initializeDiceSides($totalSides, $fair, $maxProbability = 100) { $maxTemp = $maxProbability; $sides = array(); for ($side = 0; $side < $totalSides; $side++) { //if we want fair dice just generat

我有一个通过以下代码初始化骰子对象的代码:

public function initializeDiceSides($totalSides, $fair, $maxProbability = 100) {
   $maxTemp = $maxProbability;
   $sides = array();

   for ($side = 0; $side < $totalSides; $side++) {
     //if we want fair dice just generate same probabilities for each side
     if ($fair === true) {
       $probability = number_format($maxProbability/$totalSides, 5);
     } else {
       //set probability to random number between 1 and half of $maxTemp
       $probability = number_format(mt_rand(1, $maxTemp/2), 5);

       //subtract probability of current side from maxtemp
       $maxTemp= $maxTemp- $probability;

       $sides[$side] = $probability;
     }
   }

   echo $total . '<br />';
   print_r($sides);
}
我希望能够生成浮点数而不是整数,我希望有类似的

Array ( [0] => 48.051212 [1] => 13.661212 [2] => 14.00031 
        [3] => 9.156212 [4] => 2.061512 [5] => 2.00000 )

我只需生成从0到999999的随机数,然后将它们除以100000,确保$maxProbability和$totalSides的值是浮点数。

如果它们是整数,则结果将被输入为整数。

一种简单的方法是使用
lcg\u值
与范围相乘并加上最小值

function random_float ($min,$max) {
    return ($min + lcg_value()*(abs($max - $min)));
}

您可以将输入到mt_random的变量乘以100000,然后将输出除以相同的因子,得到一个浮点值。

请参阅上的用户注释,另请参阅关于代码作用的一点解释,这将大大有助于OP和OP之后的所有社区用户查看learn@ochi想了想,但这似乎是多余的。这使用事实上的标准方法签名函数生成一个范围内的随机数。问题的作者已经知道了mt_rand的两个参数是相同的。最后,最后一个(第三个)参数实际上是不言自明的。
function random_float($min = 0, $max = 1, $includeMax = false) {
    return $min + \mt_rand(0, (\mt_getrandmax() - ($includeMax ? 0 : 1))) / \mt_getrandmax() * ($max - $min);
}
function random_float($min = 0, $max = 1, $includeMax = false) {
    return $min + \mt_rand(0, (\mt_getrandmax() - ($includeMax ? 0 : 1))) / \mt_getrandmax() * ($max - $min);
}