Why JavaScript Math.random() returns same number multiple times

前端 未结 2 617
梦如初夏
梦如初夏 2021-01-17 08:55

I have an array with two items and I need to random a choice of this items but the most of times I get the same item from array...

See the code:

var          


        
相关标签:
2条回答
  • 2021-01-17 09:46

    Random numbers can appear in streaks; that's part of being random. But over time the law of large numbers should take over and even out those streaks. You can test that easily enough by running this a bunch of times and counting:

    var numbers = Array(523,3452);
    let counts = [0,0]
    
    for (let i = 0; i < 10000; i++) {
        let choice = numbers[Math.floor(Math.random()*numbers.length)];
        if (choice ===  523) counts[0]++
        else if (choice == 3452) counts[1]++
    }
    
    // counts should be about even
    console.log(counts);

    0 讨论(0)
  • 2021-01-17 09:48

    The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.

    Math.random() * 2 will give range 0 to 1.99999999999999 but not 2. Math.floor(0...1.999999999999) will either return 0 or 1 with 50% chance similar to a coin.

    numbers[0] will give 523 and numbers[1] will give 3452

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