How does Math.random() work in javascript?

后端 未结 5 1472
谎友^
谎友^ 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:01

    It's correct that they use a "time like thing". A pseudo random generator is typically seeded using the system clock, because that is a good source of a number that isn't always the same.

    Once the random generator is seeded with a number, it will generate a series of numbers that all depending on the initial value, but in such a way that they seem random.

    A simple random generator (that was actually used in programming languages a while back) is to use a prime number in an algorithm like this:

    rnd = (rnd * 7919 + 1) & 0xffff;
    

    This will produce a series of numbers that jump back and forth, seemingly random. For example:

    seed = 1337
    36408
    22089
    7208
    63833
    14360
    11881
    41480
    13689
    6648
    

    The random generator in Javascript is just a bit more complex (to give even better distribution) and uses larger numbers (as it has to produce a number that is about 60 bits instead of 16), but it follows the same basic principle.

提交回复
热议问题