开始使用免费开始使用

从混合分布采样(I)

"混合分布"是指其密度是若干正态分布密度(组件)的线性组合的分布。每个组件都有一个"权重"(被选中的概率)、一个均值和一个标准差(与其他正态分布相同)。

您将用两个练习逐步构建该算法。本题中,您需要补全 choose_component() 的定义,用于选择要采样的组件。

本练习是课程的一部分

用 Rcpp 优化 R 代码

查看课程

练习说明

  • 使用 R 命名空间中的 runif() 函数,从 0total_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)))
*/
编辑并运行代码