PHP equivalent of javascript Math.random()

2019-04-09 02:52发布

问题:

I need a PHP function that generate random number identical to javascript Math.random() width 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.

回答1:

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?



回答2:

Javascript's Math.random gives a random number between 0 and 1. Zero is a correct output, but 1 should not be included. @thiagobraga's answer could give 1 as an output. My solution is this:

function random(){
    return mt_rand() / (mt_getrandmax() + 1);
}

This will give a random number between 0 and 0.99999999953434.



回答3:

You could try:

function random () {
    return (float)("0." . rand(1e15, 999999999999999));
}

Or even:

function random () {
   return rand(1e15, 999999999999999) / 1e15;
}

However, @elclanrs solution seems a lot easier. I tried.