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

拜拜、爱过 提交于 2020-06-08 15:42:12

问题


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 numbers = Array(523,3452);
var choice = numbers[Math.floor(Math.random()*numbers.length)];
console.log("Choice:", choice);

How can I avoid this kind of behavior?


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/51564360/why-javascript-math-random-returns-same-number-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!