jeudi 21 mars 2019

C++ equivalent to R's set.seed() function

I would like to do the equivalent of R's set.seed() inside of a C++ function. How do I do this?

Note that I make this C++ function available in R via the Rcpp package. I would like myfun(seed=42) to return the same result each time it is called in R. I do not want to set the rng seed in R via set.seed() prior to calling myfun every time.

C++ file:

#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)
*/

This currently returns:

> myfun(42)
[1] 0.737397

> myfun(42)
[1] -0.02764103

What I want is:

> myfun(42)
[1] 0.737397

> myfun(42)
[1] 0.737397




Aucun commentaire:

Enregistrer un commentaire