我有百分比10%,20%和70%決定採取何種行動。我有兩種方法來決定:#1讓一個新的Math.random()每次決定,或者#2保留一個Math.random()結果。見我在控制檯中運行的代碼(注意rand1
和rand2
方法):百分比分配 - 的JavaScript的Math.random()
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]
?
媽的這會給正確的輸出,你是對的。其實它很簡單。如果我總結18和72我得到90.而在90 - 18至72是20%至80%的比例。九十零分之十八= 0.2 = 20%。得到它了。謝謝 – spaxxUnited 2013-04-05 15:55:31