純量隨機數生成
在寫 R 程式碼時,通常會用向量化的方式產生隨機數。然而在 C++ 中,你可以放心使用迴圈,一個元素一個元素地處理資料。
R 的 API 提供了從常見機率分佈產生隨機數的函式,而 Rcpp 讓你可以在 R:: 命名空間中存取這些函式。舉例來說,R::rnorm(2, 3) 會從常態分佈(平均數為 2、標準差為 3)回傳一個隨機數。請注意,和「真正的」rnorm() 不同,這裡沒有 n 這個參數。Rcpp 的版本永遠只回傳一個數值。
來完成 positive_rnorm() 的函式定義吧。
注意:本章內容偏難,如果你第一次嘗試沒有完成練習,別氣餒。請記得完成本課程的回報:讓你的 R 程式碼效能大幅提升!
本練習屬於課程
用 Rcpp 最佳化 R 程式碼
練習說明
- 將回傳值
out指定為大小為n的數值向量。 - 先閱讀迴圈中的程式碼,理解各步驟在做什麼。
- 產生一個平均數為
mean、標準差為sd的常態隨機數,指定給out[i]。 - 當
out[i]小於或等於 0 時,持續重試。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
#include
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector positive_rnorm(int n, double mean, double sd) {
// Specify out as a numeric vector of size n
___ ___(___);
// This loops over the elements of out
for(int i = 0; i < n; i++) {
// This loop keeps trying to generate a value
do {
// Call R's rnorm()
out[i] = ___;
// While the number is negative, keep trying
} while(___);
}
return out;
}
/*** R
positive_rnorm(10, 2, 2)
*/