Node.js中的分布抽样 [英] distributional sampling in Node.js
本文介绍了Node.js中的分布抽样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何在Node.js中执行分布抽样。
I wonder how it's possible to perform distributional sampling in Node.js.
特别是,我有元素数量,其中元素的第i个值数组是第i个元素的概率,例如,
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]
现在我需要执行采样,并且一半样本的采样结果应为0.2的样本中的2为0,在0.3个样本中是1。
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.
推荐答案
传统方法:
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();
…
这篇关于Node.js中的分布抽样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文