Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong if not including GetRNGstate()?

Tags:

r

rcpp

GetRNGstate() and PutRNGstate() are mysteries to me. I have read section 6.3 of Writing R Extensions but it only says "the user must call" them and "These essentially read in (or create) .Random.seed and write it out after use".

I initially thought that if I failed to include them then the set.seed() function in R will not be able to work on my Rcpp function. So I did some experiments but it turns out that nothing seems wrong without GetRNGstate() and PutRNGstate(). I feel that I must be missing something, so why and when should I include these two functions?

Below is my own experiment:

// [[Rcpp::export]]
NumericVector myrv4(int n) {
  NumericVector x = rnorm(n, 0.0, 1.0);
  return x;
}

And my test results:

> n <- 2
> set.seed(1234)
> myrv4(n)
[1] -1.2070657  0.2774292
> set.seed(1234)
> myrv4(n)
[1] -1.2070657  0.2774292
like image 938
Bayesric Avatar asked Feb 08 '23 14:02

Bayesric


1 Answers

You missed the fact that using Rcpp Attributes includes it for you anyway, as it should. Try building with , verbose=TRUE to see

 Rcpp::RNGScope __rngScope

inserted auto-magic-ally for you.

like image 172
Dirk Eddelbuettel Avatar answered Feb 16 '23 03:02

Dirk Eddelbuettel