我有10%、20%和70%的百分比来决定要采取的行动。我有两种方法来决定:#1 每次都让一个新的 Math.random() 决定,或者 #2 保留一个 Math.random() 结果。查看我在控制台中运行的代码(注意rand1
andrand2
方法):
console.log('chart1');
var chart1;
var rand1 = function() {
if (Math.random() <= 0.1) chart1[0]++;
else if (Math.random() <= 0.2) chart1[1]++;
else chart1[2]++;
};
var runs = 10000;
for (var j = 0; j < 10; j++) {
chart1 = [0,0,0];
for (var i = 0; i < runs; i++) rand1();
var log = [];
for (var k = 0; k < chart1.length; k++) {
log[k] = Math.round(chart1[k] / runs * 100);
}
console.log(log);
}
console.log('chart2');
var chart2;
var rand2 = function() {
var rand = Math.random();
if (rand <= 0.1) chart2[0]++;
else if (rand >= 0.1 && rand <= 0.3) chart2[1]++;
else chart2[2]++;
};
var runs = 10000;
for (var j = 0; j < 10; j++) {
chart2 = [0,0,0];
for (var i = 0; i < runs; i++) rand2();
var log = [];
for (var k = 0; k < chart2.length; k++) {
log[k] = Math.round(chart2[k] / runs * 100);
}
console.log(log);
}
它产生
chart1
[10, 18, 72]
[10, 17, 72]
[11, 17, 72]
[10, 18, 72]
[10, 18, 72]
[10, 18, 72]
[10, 17, 73]
[10, 18, 72]
[10, 18, 72]
[10, 18, 71]
chart2
[9, 20, 71]
[10, 21, 70]
[10, 19, 71]
[10, 20, 70]
[10, 19, 71]
[10, 20, 70]
[10, 20, 70]
[9, 20, 71]
[10, 20, 71]
[9, 20, 71]
我不明白为什么chart1
倾向于..18, 72]
?