问题
I wonder how it's possible to perform distributional sampling in Node.js.
In particular, I have the number of elements, where the i'th value of the arrays is the probability of the element i'th, like following
[0.2 0.3 0.5]
Now I need to perform sampling, and the result of the sampling in half of the samples should be 2 in 0.2 of the samples is 0 and in 0.3 of the samples is 1.
回答1:
Trivial method:
function distribute(probs) {
return function() {
var r = Math.random();
var i = 0,
acc = 0;
while ((acc += probs[i]) <= r)
i++;
return i;
};
}
var sample = distribute([0.2, 0.3, 0.5]);
sample();
sample();
sample();
…
来源:https://stackoverflow.com/questions/22863565/distributional-sampling-in-node-js