ComenzarEmpieza gratis

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 ejercicio forma parte del curso

Optimizing R Code with Rcpp

Ver curso

Instrucciones del ejercicio

  • Generate a uniform random number from 0 to total_weight using the runif() function in the R namespace.
  • Inside the while loop, decrease the value of x by the jth element of weights.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

#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)))
*/
Editar y ejecutar código