LoslegenKostenlos loslegen

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().

Diese Übung ist Teil des Kurses

Optimizing R Code with Rcpp

Kurs anzeigen

Anleitung zur Übung

  • 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.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

#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)))
*/
Code bearbeiten und ausführen