How does Math.random() work in javascript?

后端 未结 5 1466
谎友^
谎友^ 2020-11-30 08:23

I recently figured out how to get a random number via google, and it got me thinking how does Math.random() work. So here I am I can not figure out how they did

5条回答
  •  [愿得一人]
    2020-11-30 09:28

    you may want this article for a reference: https://hackernoon.com/how-does-javascripts-math-random-generate-random-numbers-ef0de6a20131

    And btw, recently I am also curious about this question and then read the source code of NodeJS. We can know one possible implementation from Google V8:

    The main entry for the random (MathRandom::RefillCache function): https://github.com/v8/v8/blob/master/src/math-random.cc

    How the seed initialized? see also here: https://github.com/v8/v8/blob/master/src/base/utils/random-number-generator.cc#L31

    The key function is (XorShift128 function): https://github.com/v8/v8/blob/master/src/base/utils/random-number-generator.h#L119

    in this header file, there are references to some papers:

    // See Marsaglia: http://www.jstatsoft.org/v08/i14/paper
    // And Vigna: http://vigna.di.unimi.it/ftp/papers/xorshiftplus.pdf
    

提交回复
热议问题