混合分布からのサンプリング(I)
「混合分布」は、複数の正規分布(成分)の密度を線形結合した分布です。各成分には、選ばれる確率である「重み」と、平均・標準偏差(通常の正規分布と同様)があり ます。
このアルゴリズムは2つの演習で段階的に作成します。ここでは、choose_component() の定義を完成させて、サンプルを生成する成分を選ぶ処理を実装します。
この演習はコースの一部です
Rcpp で R コードを最適化する
演習の手順
R名前空間のrunif()関数を使って、0からtotal_weightまでの一様乱数を生成します。- while ループの中で、
xからweightsの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)))
*/