เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

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

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Optimizing R Code with Rcpp

ดูคอร์ส

คำแนะนำการฝึกหัด

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

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

#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)))
*/
แก้ไขและรันโค้ด