開始使用免費開始

從混合分配取樣(I)

「混合分配」是一種其機率密度為多個常態分配密度(元件)的線性組合的分配。每個元件都有一個「權重」(被選中的機率)、一個平均數,以及一個標準差(與一般常態分配相同)。

你將用兩個練習逐步完成這個演算法。此處請完成 choose_component() 的定義,以選出要取樣的元件。

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 使用 R 命名空間中的 runif(),從 0total_weight 產生一個均勻亂數。
  • 在 while 迴圈中,將 xweights 的第 j 個元素遞減。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

#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)))
*/
編輯並執行程式碼