Sampling from a mixture of distributions (I)
A mixture distribution is a distribution whose density is a linear combination of normal distribution densities (components). Each component has a weight (its probability of being chosen), and a mean and standard deviation (just like any other normal distribution).
You'll build up the algorithm over two exercises. Here you'll choose the component to sample from by completing the definition of choose_component().
Este exercício faz parte do curso
Optimizing R Code with Rcpp
Instruções do exercício
- Generate a uniform random number from
0tototal_weightusing therunif()function in theRnamespace. - Inside the while loop, decrease the value of
xby thejth element ofweights.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
#include
using namespace Rcpp;
// [[Rcpp::export]]
int choose_component(NumericVector weights, double total_weight) {
// Generate a uniform random number from 0 to total_weight
double x = ___::___(0, ___);
// Remove the jth weight from x until x is small enough
int j = 0;
while(x >= weights[j]) {
// Subtract jth element of weights from x
___;
j++;
}
return j;
}
/*** R
weights <- c(0.3, 0.7)
# Randomly choose a component 5 times
replicate(5, choose_component(weights, sum(weights)))
*/