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.
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.
rand() or mt_rand() functions can be used to Generate 5 Digit Random Number in PHP.
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.
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).
You could use a function that returns the value:
function random() {
return (float)rand()/(float)getrandmax();
}
// Generates
// 0.85552537614063
// 0.23554185613575
// 0.025269325846126
// 0.016418958098086
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?
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