我想在C ++中为n个数字定义一个特定的概率密度函数(pdf),然后在我的代码中选择其中一些。
我的pdf是:P(x)=(1 / logn)* f(x)^( - 2)
f(x)具有一个确定性数字,该数字已在我的代码中为每个x确定。
我更喜欢使用标准库函数,因为我应该在计算机集群中使用我的程序,使用其他库(例如boost)可能会在该集群中产生更多问题。
我找到的初始代码是:
for(int x=1;x<n+1;x++){
// I calculate all f(x) and therefore P(x) here
}
std::default_random_engine generator;
std::discrete_distribution<int> distribution { .. not sure how to use P(x)s here .. };
int prob[n]={};
for (int i=0; i<n; ++i) {
int number = distribution(generator);
++prob[number];
}
非常感谢提前。
答案 0 :(得分:3)
您现在可以使用权重构建向量:
std::vector< double> weights( n);
for( int i = 0; i < n; ++i) {
weights[i] = pdf( i + 1);
}
std::default_random_engine generator;
std::discrete_distribution<int> distribution( weights.begin(), weights.end()) ;
int prob[n]={};
for ( int i=0; i<n; ++i) {
int number = distribution( generator);
++prob[number];
}
这将从0开始生成,这就是discrete_distribution的工作原理,但是您可以假设在不失去正确性的情况下计算范围1, ..., n
的值(计算1, ..., n
的权重)。 / p>