我有一个通过以下代码初始化骰子对象的代码:
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 )
一个简单的方法是使用
lcg_value
并乘以范围并添加最小值
function random_float ($min,$max) {
return ($min + lcg_value()*(abs($max - $min)));
}
我只是生成 0 到 999999 之间的随机数,然后将它们除以 100000
您可以将输入到
mt_random
的变量乘以一个系数,例如 100000,然后将输出除以相同的系数以获得浮点值。
function random_float($min = 0, $max = 1, $includeMax = false) {
return $min + \mt_rand(0, (\mt_getrandmax() - ($includeMax ? 0 : 1))) / \mt_getrandmax() * ($max - $min);
}