The problem is to select k items with-replacement from a list of n items with a probability that depends on the weights associated with the items in the original list.
Input: x[n], w[n]
Output: x[n] (x is overwritten)
void wrswr(gsl_rng *r, std::vector
{
if(x.size() != w.size())
{
cerr << "w and x must have same length ..." << endl;
exit(-1);
}
else
{
size_t N = (size_t)x.size();
std::vector
double sum_w = 0.0;
for(size_t i = 0; i < N; ++i)
{
sum_w += w.at(i);
tempx.at(i) = x.at(i); // copy of source xk
}
for(size_t i = 0; i < N; ++i)
{
double u = gsl_rng_uniform(r);
size_t j = 0;
double c = w[0] / sum_w;
while (u > c && j < N)
{
j = j + 1;
c = c + w[j] / sum_w;
}
x.at(i) = tempx.at(j);
}
}
}
Weighted Random Sampling |
1 comment:
Post a Comment