从混合分布采样(II)
从混合分布采样的完整算法如下:
- 选择一个分量。
- 使用所选分量的均值和标准差生成一个正态随机数。
上一个练习中的 choose_component() 已提供。这里您将完成第二步,并补全 rmix() 的定义。
本练习是课程的一部分
用 Rcpp 优化 R 代码
练习说明
- 检查标准差的数量是否与权重相同。也就是说,
sds的大小应与d相同。 - 将权重求和得到
total_weight。 - 调用
choose_component()选择一个分量。 - 使用
means和sds的第j个元素生成一个正态随机数,从所选分量进行模拟。
交互式实操练习
通过完成这段示例代码来试试这个练习。
#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)
*/