Ita*_*lux -4 javascript math node.js
我有一个包含两个项目的数组,我需要随机选择这些项目,但大多数时候我从数组中得到相同的项目...
看代码:
var numbers = Array(523,3452);
var choice = numbers[Math.floor(Math.random()*numbers.length)];
console.log("Choice:", choice);
Run Code Online (Sandbox Code Playgroud)
我该如何避免这种行为?
Mar*_*yer 10
随机数可以出现在条纹中; 这是随机的一部分.但随着时间的推移,大数法则应该接管并消除这些条纹.您可以通过多次运行并计算来轻松测试:
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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2270 次 |
| 最近记录: |