How does one generate a random float between 0 and 1 in PHP?
I'm looking for the PHP's equivalent to Java's Math.random()
.
php function rand_float($st_num=0,$end_num=1,$mul=1000000) { if ($st_num>$end_num) return false; return mt_rand($st_num*$mul,$end_num*$mul)/$mul; } echo rand_float(). "\n"; echo rand_float(0.6). "\n"; echo rand_float(0.5,0.6). "\n"; echo rand_float(0,20).
The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.
The random() function generates a random float number between 0.0 to 1.0 but never returns the upper bound. I.e., It will never generate 1.0. On the other side, the uniform(start, stop) generates any random float number between the given start and stop number.
You may use the standard function: lcg_value().
Here's another function given on the rand() docs:
// auxiliary function // returns random number with flat distribution from 0 to 1 function random_0_1() { return (float)rand() / (float)getrandmax(); }
Example from documentation :
function random_float ($min,$max) { return ($min+lcg_value()*(abs($max-$min))); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With