Why is Google Chrome's Math.random number generator not *that* random?

后端 未结 3 1598
挽巷
挽巷 2020-12-05 11:03

I ran into an odd \"bug\" today when I was running some unit tests in various browsers. I had run the tests in Firefox many times before today, and even IE but apparently no

相关标签:
3条回答
  • 2020-12-05 11:05

    Other answers have explained the issue. If you're after better pseudo-random number generation in JavaScript, I'd recommend this page as a good place to start:

    http://baagoe.com/en/RandomMusings/javascript/

    I adapted one of the algorithms on this page for a script I'm using to generate UUIDs in the browser and had no collisions in my tests.

    UPDATE 22 October 2013

    The pages linked to above are no longer live. Here's a link to a snapshot from the Wayback Machine:

    http://web.archive.org/web/20120502223108/http://baagoe.com/en/RandomMusings/javascript/

    And here's a link to a Node.js module that includes Alea.js:

    https://npmjs.org/package/alea

    0 讨论(0)
  • 2020-12-05 11:12

    See https://medium.com/@betable/tifu-by-using-math-random-f1c308c4fd9d:

    If we analyze the first sub-generator independently we see that it has 32 bits of internal state. It’s not a full-cycle generator — its actual cycle length is about 590 million (18,030*2¹⁵-1, the math is tricky but it’s explained here and here, or you can just trust me). So we can only produce a maximum of 590 million distinct request identifiers with this generator. If they were randomly selected there would be a 50% chance of collision after generating just 30,000 identifiers.

    0 讨论(0)
  • 2020-12-05 11:22

    Apparently Math.random() in V8 only works with 32 bit values (and didn't even correctly randomize all of those in the past). And with 32 bits, the probability of a collision reaches 50% around 2^16 = 65k values...

    0 讨论(0)
提交回复
热议问题