我有一些奇怪的错误,我无法理解它来自哪里。我在Google Script环境中将它写入js。在javascript中从pdf中选择一个随机变量
function tester() {
var pdf = [[0,5],[1,5],[2,40],[3,50]]; // some pdf as a 2d array
var tuple = [0,0,0,0]; //the resulting pdf from the test
var rand = 0;
for (var i = 0; i<100; i++){ //100 times initialize a random variable and then catch the result into the tuple
rand = getRandomN(pdf);
if (rand==0){tuple[0]+=1} //if the outcome==0 then add 1 to the first element of the tuple
else if (rand==1){tuple[1]+=1}
else if (rand==2){tuple[2]+=1}
else if (rand==3){tuple[3]+=1}
}
Logger.log(tuple);
}
getRandomN(pdf)
返回根据PDF
问题的一个结果是,元组始终返回1全零的一些地方。它看起来像随机发生器工作得很好,但循环只经过一次。 有没有人有提示?
UPDATE:
function getRandomN(pdf) {
var result = 0;
var rand = getRandomInt(0,10000)/100;
for (var i=1; i<pdf.length; i++){
pdf[i][1] = pdf[i][1] + pdf[i-1][1];
}
if (pdf[pdf.length-1][1] != 100){return undefined}
//Logger.log(rand);
for (var i=0; i<pdf.length; i++){
if (rand<=pdf[i][1]){result=pdf[i][0]; break}
}
Logger.log(pdf);
return result;
}
而且从Mozilla的
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
其中getRandomN如果可能的话也显示这部分。 – 2015-01-15 15:20:05
我会立即添加它。这只是它工作得很好,如果我简单地测试它没有循环,但循环有点跳过。 – AVX 2015-01-15 15:23:33
你的循环对我来说看起来很好......你写了getRandomN()吗?我们可以看到那个代码吗?另外,如果你知道getRandomN()只会返回与你的元组索引相匹配的值,你可以用一行代替整个循环的内部: 'tuple [getRandomN(pdf)] + = 1; ' – 2015-01-15 15:25:55