我想从相对较大的人群中抽取 n 个样本而不进行替换。所以我绘制随机数并跟踪我之前的选择,这样每当我两次绘制一个数字时我都可以重新采样:
boost::mt19937 generator;
boost::uniform_int<> distribution(0, 1669 - 1);
boost::variate_generator<boost::mt19937, boost::uniform_int<> >
gen(generator, distribution);
int n = 100;
std::vector<int> idxs;
while(static_cast<int>(idxs.size()) < n)
{
// get random samples
std::generate_n(std::back_inserter(idxs), n - idxs.size(),
gen);
// remove duplicates
// keep everything that's not duplicates to save time
std::sort(idxs.begin(), idxs.end());
std::vector<int>::iterator it = std::unique(idxs.begin(), idxs.end());
idxs.resize(std::distance(idxs.begin(), it));
}
不幸的是,我遇到了上面使用的常量的无限循环。
我添加了一些输出(表明它一直选择相同的数字)并在 10 次尝试后停止以显示问题:
boost::mt19937 generator;
boost::uniform_int<> distribution(0, 1669 - 1);
boost::variate_generator<boost::mt19937, boost::uniform_int<> >
gen(generator, distribution);
int n = 100;
int repeat = 0;
std::vector<int> idxs;
while(static_cast<int>(idxs.size()) < n)
{
if(repeat++ > 10) break;
cout << "repeat " << repeat <<
", " << idxs.size() << " elements" << endl;
std::generate_n(std::back_inserter(idxs), n - idxs.size(),
gen);
cout << "last " << idxs.back() << endl;
std::sort(idxs.begin(), idxs.end());
std::vector<int>::iterator it = std::unique(idxs.begin(), idxs.end());
idxs.resize(std::distance(idxs.begin(), it));
}
代码打印
repeat 1, 0 elements
last 1347
repeat 2, 99 elements
last 1359
repeat 3, 99 elements
last 1359
等等,如果我不杀死程序,这似乎永远循环。这不应该发生,对吧?我只是不走运吗?还是我做错了什么?
简短的解决方案 感谢@jxh!使用参考有助于:
boost::variate_generator<boost::mt19937&, boost::uniform_int<> >
gen(generator, distribution);