0至1.0 php之间的随机浮点数
可能重复:
PHP中的随机浮动
是否可以在0到1.0之间创建一个随机浮点数,例如0.4、0.8等。我使用了rand,但是它只接受整数。
7个解决方案
94 votes
mt_rand() / mt_getrandmax();
避免使用rand()函数,因为它通常取决于平台的C rand()实现,通常使用非常简单的模式创建数字。 在php.net上看到此评论
Francois Bourgeois answered 2020-06-22T01:25:40Z
24 votes
那么简单地除以10呢?
$randomFloat = rand(0, 10) / 10;
var_dump($randomFloat);
//eg. float(0.7)
h2ooooooo answered 2020-06-22T01:26:00Z
8 votes
$v = mt_rand() / mt_getrandmax();
会做到的。
如果您只想要小数点后一位(例如在问题示例中),则只需获得round()的值即可...
$v = round( $v, 1 );
...或计算0到10之间的数字并除以10:
$v = mt_rand( 0, 10 ) / 10;
Paolo answered 2020-06-22T01:26:29Z
3 votes
根据PHP文档,如果您使用的是PHP 7,则可以使用random_int生成加密安全的伪随机整数
话虽如此,这是一个函数,利用该函数在两个数字之间生成随机浮点数:
function random_float($min, $max) {
return random_int($min, $max - 1) + (random_int(0, PHP_INT_MAX - 1) / PHP_INT_MAX );
}
尽管random_int()比mt_rand()更安全,但请记住,它也较慢。
该答案的先前版本建议您使用PHP rand(),并且实现糟糕。 我想改变我的答案,而不必重复别人已经说过的话,现在我们到了。
Nemo Caligo answered 2020-06-22T01:27:02Z
2 votes
这个简单的解决方案怎么样:
abs(1-mt_rand()/mt_rand())
要么
/**
* Generate Float Random Number
*
* @param float $Min Minimal value
* @param float $Max Maximal value
* @param int $round The optional number of decimal digits to round to. default 0 means not round
* @return float Random float value
*/
function float_rand($Min, $Max, $round=0){
//validate input
if ($min>$Max) { $min=$Max; $max=$Min; }
else { $min=$Min; $max=$Max; }
$randomfloat = $min + mt_rand() / mt_getrandmax() * ($max - $min);
if($round>0)
$randomfloat = round($randomfloat,$round);
return $randomfloat;
}
Dracony answered 2020-06-22T01:27:26Z
2 votes
试试这个
// Generates and prints 100 random number between 0.0 and 1.0
$max = 1.0;
$min = 0.0;
for ($i = 0; $i < 100; ++$i)
{
print ("
");
$range = $max - $min;
$num = $min + $range * (mt_rand() / mt_getrandmax());
$num = round($num, 2);
print ((float) $num);
}
Nandu answered 2020-06-22T01:27:46Z
1 votes
强制转换为float *,然后除以getrandmax()。
*在PHP的任意类型变戏法规则中,似乎不需要强制转换。 但是,它将使用其他语言。
Oliver Charlesworth answered 2020-06-22T01:28:10Z