Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Float between 0 and 1 in PHP

Tags:

php

random

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().

like image 218
Goaler444 Avatar asked Jan 03 '13 14:01

Goaler444


People also ask

How to generate random float number in php?

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

How do I randomize in php?

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.

Which of the following code snippets will create a random floating number between 0 and 1?

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.


2 Answers

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(); } 
like image 55
3 revs, 3 users 79% Avatar answered Sep 29 '22 04:09

3 revs, 3 users 79%


Example from documentation :

function random_float ($min,$max) {    return ($min+lcg_value()*(abs($max-$min))); } 
like image 24
Pierrickouw Avatar answered Sep 29 '22 03:09

Pierrickouw