LoslegenKostenlos loslegen

Stichproben aus einer Mischverteilung (II)

Der vollständige Algorithmus zum Ziehen von Stichproben aus einer Mischverteilung lautet:

  1. Wähle eine Komponente.
  2. Erzeuge eine normalverteilte Zufallszahl mit dem Mittelwert und der Standardabweichung der ausgewählten Komponente.

choose_component() aus der letzten Übung ist gegeben. Hier vervollständigst du den zweiten Schritt und die Definition von rmix().

Diese Übung ist Teil des Kurses

R-Code mit Rcpp optimieren

Kurs anzeigen

Anleitung zur Übung

  • Prüfe, dass es genauso viele Standardabweichungen wie Gewichte gibt. Das heißt, die Größe von sds entspricht d.
  • Berechne total_weight als Summe der Gewichte.
  • Wähle eine Komponente, indem du choose_component() aufrufst.
  • Simuliere aus der gewählten Komponente, indem du eine normalverteilte Zufallszahl mit dem j-ten Element von means und sds erzeugst.

Interaktive Übung

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

#include 
using namespace Rcpp;

// From previous exercise; do not modify
// [[Rcpp::export]]
int choose_component(NumericVector weights, double total_weight) {
  double x = R::runif(0, total_weight);
  int j = 0;
  while(x >= weights[j]) {
    x -= weights[j];
    j++;
  }
  return j;
}

// [[Rcpp::export]]
NumericVector rmix(int n, NumericVector weights, NumericVector means, NumericVector sds) {
  // Check that weights and means have the same size
  int d = weights.size();
  if(means.size() != d) {
    stop("means size != weights size");
  }
  // Do the same for the weights and std devs
  if(___) {
    stop("sds size != weights size");
  }
  
  // Calculate the total weight
  double total_weight = ___;
  
  // Create the output vector
  NumericVector res(n);
  
  // Fill the vector
  for(int i = 0; i < n; i++) {
    // Choose a component
    int j = ___(___, ___);
    
    // Simulate from the chosen component
    res[i] = ___::___(___, ___);
  }
  
  return res;
}

/*** R
  weights <- c(0.3, 0.7)
  means <- c(2, 4)
  sds <- c(2, 4)
  rmix(10, weights, means, sds)
*/
Code bearbeiten und ausführen