Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent of javascript Math.random()

I need a PHP function that generates random number identical to javascript Math.random() with the same seed.

MDN about math.random():

The random number generator is seeded from the current time, as in Java.

As far I tried the PHP's rand() generates something like that:

srand( time() ); // I use time as seed, like javascript does
echo rand();
Output: 827382

And javascript seems to generate random numbers on it's own way:

Math.random(); Output: 0.802392144203139

I need PHP code that is equivalent for math.random(), not new javascript code. I can't change javascript.

like image 750
Mateusz Biłgorajski Avatar asked Jul 17 '13 02:07

Mateusz Biłgorajski


People also ask

What is random function 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.

How can I generate 5 random numbers in PHP?

rand() or mt_rand() functions can be used to Generate 5 Digit Random Number in PHP.

Is Math random really random JavaScript?

How random is Math. random()? It may be pointed out that the number returned by Math. random() is a pseudo-random number as no computer can generate a truly random number, that exhibits randomness over all scales and over all sizes of data sets.

How do I generate a random 4 digit number in PHP?

Generate 4 Digit Random Number using mt_rand() mt_rand() function is just like rand() function but it is 4 times faster than rand() function. To use mt_rand() function define min and max numbers. The mt_rand() function will return a random integer between min and max numbers (including min and max numbers).


1 Answers

You could use a function that returns the value:

PHP

function random() {
  return (float)rand()/(float)getrandmax();
}

// Generates
// 0.85552537614063
// 0.23554185613575
// 0.025269325846126
// 0.016418958098086


JavaScript

var random = function () {
  return Math.random();
};

// Generates
// 0.6855146484449506
// 0.910828611580655
// 0.46277225855737925
// 0.6367355801630765

@elclanrs solution is easier and doesn't need the cast in return.


Update

There's a good question about the difference between PHP mt_rand() and rand() here:
What's the disadvantage of mt_rand?

like image 158
thiagobraga Avatar answered Oct 19 '22 23:10

thiagobraga