gpt4 book ai didi

Rcpp 将 RNG 状态设置为以前的状态

转载 作者:行者123 更新时间:2023-12-02 00:00:05 24 4
gpt4 key购买 nike

我的问题是http://rcpp-devel.r-forge.r-project.narkive.com/qJMEsvOK/setting-the-r-random-seed-from-rcpp的后续问题.

我希望能够从 C++ 中将 RNG 状态设置为以前的状态。例如,我希望以下代码生成一个矩阵,其中每列都包含 Gamma 随机变量的相同实现。

cppFunction('NumericMatrix rgamma_reset_seed(int n, double shape, double rate){
RNGScope rngscope;
Environment g = Environment::global_env();
Environment::Binding RandomSeed = g[".Random.seed"];
IntegerVector someVariable = RandomSeed;
NumericMatrix results(n, 2);
results(_,0) = rgamma(n, shape, 1/rate);
RandomSeed = someVariable;
results(_,1) = rgamma(n, shape, 1/rate);
return results;
}')
m <- rgamma_reset_seed(1000, 1.2, 0.8)
par(mfrow = c(2, 1))
plot(m[,1])
plot(m[,2])

但是好像不行。在 R 中,我可以通过诸如

之类的行来实现结果
.Random.seed <- x # reset the state to x
x <- .Random.seed # store the current state

我是否遗漏了一些明显的东西?任何帮助将不胜感激!

最佳答案

这可能行不通(容易)——Writing R Extension 中有一些语言指出您无法从 C 级 API 设置种子。

现在,你可以作弊:

  1. 从 R 初始化 RNG
  2. 做一些工作,确保它像我们的代码一样被 RNGScope 包装。
  3. 现在作弊并使用 Rcpp::Function() 调用 set.seed()
  4. 考虑是否返回第 2 步或完成。

关于Rcpp 将 RNG 状态设置为以前的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30466462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com