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

时间:2013-12-03 22:49:45

标签: 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 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);
}

以上代码打印:

89
Array ( [0] => 48.00000 [1] => 13.00000 [2] => 14.00000 
        [3] => 9.00000 [4] => 2.00000 [5] => 2.00000 )

我希望能够生成浮点数而不是整数,我希望有类似

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

5 个答案:

答案 0 :(得分:9)

一种简单的方法是使用lcg_value并乘以范围并添加最小值

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

答案 1 :(得分:3)

我只生成从0到999999的随机数,然后将它们除以100000

答案 2 :(得分:1)

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

答案 3 :(得分:1)

function random_float($min = 0, $max = 1, $includeMax = false) {
    return $min + \mt_rand(0, (\mt_getrandmax() - ($includeMax ? 0 : 1))) / \mt_getrandmax() * ($max - $min);
}

答案 4 :(得分:-1)

确保$ maxProbability和$ totalSides的值为浮点数 如果它们是整数,则结果将被输入为整数。