Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
876 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...