Random float number between 0 and 1.0 php [duplicate]

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.

4

7 Answers

mt_rand() / mt_getrandmax();

Avoid the rand() function, since it usually depends on the platform's C rand() implementation, generally creating numbers with a very simple pattern. See this comment on php.net

Update: In php 7.1 the rand()has been changed and is now merely an alias of mt_rand(). Therefore it is now ok to use rand(), too.

4

What about simply dividing by 10?

$randomFloat = rand(0, 10) / 10;
var_dump($randomFloat);
//eg. float(0.7)
5
$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 10 and divide by 10:

$v = mt_rand( 0, 10 ) / 10;

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.

2

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;
}
4

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);
}

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. 2

You Might Also Like