为什么JavaScript Math.random()多次返回相同的数字 [英] Why JavaScript Math.random() returns same number multiple times
本文介绍了为什么JavaScript Math.random()多次返回相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含两个项目的数组,我需要随机选择一个项目,但是大多数情况下,我会从数组中获得相同的项目...
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...
查看代码:
var numbers = Array(523,3452);
var choice = numbers[Math.floor(Math.random()*numbers.length)];
console.log("Choice:", choice);
如何避免这种行为?
推荐答案
随机数可以出现在条纹中;那是随机的一部分.但是随着时间的流逝,大数定律应该取代甚至消除这些条纹.您可以通过多次运行并计数来轻松地进行测试:
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);
这篇关于为什么JavaScript Math.random()多次返回相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文