distributional sampling in Node.js

别说谁变了你拦得住时间么 提交于 2019-12-25 16:42:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!