Random float number between 0 and 1.0 php [duplica

2019-01-14 00:45发布

Possible Duplicate:
Random Float in php

Is it possible to create a random float number between 0 and 1.0 e.g 0.4, 0.8 etc. I used rand but it only accepts integers.

7条回答
干净又极端
2楼-- · 2019-01-14 00:49
$v = mt_rand() / mt_getrandmax();

will do that.


In case you want only one decimal place (as in the examples from the question) just round() the value you get...

$v = round( $v, 1 );

...or calculate a number between 0 and 100 and divide by 10:

$v = mt_rand( 0, 100 ) / 10;
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-14 00:53

Try this

// 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 ("<br>");
    $range = $max - $min;
    $num = $min + $range * (mt_rand() / mt_getrandmax());    
    $num = round($num, 2);
    print ((float) $num);
}
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-14 01:00

What about simply dividing by 10?

$randomFloat = rand(0, 10) / 10;
var_dump($randomFloat);

//eg. float(0.7)
查看更多
Luminary・发光体
5楼-- · 2019-01-14 01:01

how about this simple solution:

abs(1-mt_rand()/mt_rand()) 

or

/**
 * 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;
}
查看更多
放荡不羁爱自由
6楼-- · 2019-01-14 01:07

According to the PHP documentation, if you're using PHP 7 you can generate a cryptographically secure pseudorandom integer using random_int

With that said, here's a function that utilizes this to generate a random float between two numbers:

function random_float($min, $max) {
    return random_int($min, $max - 1) + (random_int(0, PHP_INT_MAX - 1) / PHP_INT_MAX );
}

Although random_int() is more secure than mt_rand(), keep in mind that it's also slower.

A previous version of this answer suggested you use PHP rand(), and had a horrible implementation. I wanted to change my answer without repeating what others had already stated, and now here we are.

查看更多
叛逆
7楼-- · 2019-01-14 01:08

Cast to float* and divide by getrandmax().


* It seems that the cast is unnecessary in PHP's arbitrary type-juggling rules. It would be in other languages, though.

查看更多
登录 后发表回答