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()
.
Cet exercice fait partie du cours
Optimizing R Code with Rcpp
Instructions
- Generate a uniform random number from
0
tototal_weight
using therunif()
function in theR
namespace. - Inside the while loop, decrease the value of
x
by thej
th element ofweights
.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
#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)))
*/