简体   繁体   English

Javascript - for循环中的Math.random

[英]Javascript - Math.random in a for loop

Just ran into a something interesting in Javascript while experimenting with generating a random number in the condition (is that what it's called?) of a for loop. 刚尝试在Javascript中尝试生成一个有趣的东西,同时在for循环中生成一个随机数(就像它叫做什么?)。

So, if I were to write the code like this: 所以,如果我要写这样的代码:

for (var i = 0; i < 20; i++) {
    var count = 0;
    for (var j = 0; j < Math.floor(Math.random() * 20); j++) {
        count++;
    }
    console.log(count);
}

It would return a result like this: 它将返回如下结果:

9
5
8
3
3
2
6
8
4
4
5
6
3
3
5
3
4
5
3
11

But if I were to generate a random number in a variable before the second for loop: 但是,如果我在第二个for循环之前在变量中生成一个随机数:

for (var i = 0; i < 20; i++) {
    var count = 0;
    var loopEnd = Math.floor(Math.random() * 20 + 1);
    for (var j = 0; j < loopEnd; j++) {
        count++;
    }
    console.log(count);
}

It would return a result like this: 它将返回如下结果:

11
13
14
2
19
19
17
19
2
18
5
15
18
2
1
19
16
15
13
20

What exactly is happening here? 到底发生了什么? It had me confused for a little while. 它让我困惑了一会儿。 Is the Math.random() inside the for loop generating a new random number after each iteration? for循环中的Math.random()是否在每次迭代后生成一个新的随机数? Does the loop run the code, iterate, and check the condition, and generate a new random number each time it is checking the condition? 循环是否运行代码,迭代并检查条件,并在每次检查条件时生成一个新的随机数? Is this what is happening and is this why the numbers in the console are smaller than if I use Math.random() in a variable before the for loop? 这是发生了什么,这就是为什么控制台中的数字小于在for循环之前在变量中使用Math.random()的原因?

In the first example's inner loop: 在第一个例子的内循环中:

...
for (var j = 0; j < Math.floor(Math.random() * 20); j++) {
    count++;
}
...

the termination condition j < Math.floor(Math.random() * 20) is evaluated each iteration of the loop, and so the termination value is changing each iteration with the call to Math.random() making it more likely that the loop will terminate earlier. 在循环的每次迭代中评估终止条件j < Math.floor(Math.random() * 20) ,因此终止值通过调用Math.random()改变每次迭代,使得循环更可能将提前终止。

As for the loop terminating earlier on average when the random number is chosen anew every iteration: 至于在每次迭代时重新选择随机数时,循环平均提前终止:

Without getting into proper statistical analysis, consider this simple train of thought: 没有进行适当的统计分析,请考虑这个简单的思路:

How likely are you to get ten or more iterations? 您有多大可能获得十次或更多次迭代?

If you draw just one random number between 1 and 20, you'll get 10 or more about 50% of the time. 如果你只画一个介于1和20之间的随机数,那么大约50%的时间会得到10或更多。

If you get ten random numbers you need to have each of them higher than first 1, then 2, then 3 and so on, and the odds are reduced: 95% * 90% * 85% * ... * 50%. 如果你得到10个随机数,你需要让它们分别高于第1个,然后是2个,然后是3个,依此类推,并且几率降低:95%* 90%* 85%* ...... * 50%。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM