首页 > 解决方案 > C++ 等价于 R 的 set.seed() 函数

问题描述

我想在set.seed()C++ 函数中做相当于 R 的事情。我该怎么做呢?

请注意,我通过 Rcpp 包使这个 C++ 函数在 R 中可用。我想myfun(seed=42)每次在 R 中调用它时都返回相同的结果。我不想在每次set.seed()调用之前在 R 中设置 rng 种子。myfun

C++ 文件:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double myfun(double seed) {
  std::srand(seed); // <-- this doesn't do what i want
  return R::rnorm(0,1);
}

/*** R
myfun(42)
myfun(42)
*/

这当前返回:

> myfun(42)
[1] 0.737397

> myfun(42)
[1] -0.02764103

我想要的是:

> myfun(42)
[1] 0.737397

> myfun(42)
[1] 0.737397

标签: c++rrandomrcpp

解决方案


推荐阅读