[Rcpp-devel] mixing R's and C++'s RNGs and distributions

Ramon Diaz-Uriarte rdiaz02 at gmail.com
Thu Jun 18 14:34:14 CEST 2015


Dear All,

Sometimes I use both R's and C++11's RNGs and distributions in the same
code base (I am not using OpenMP or similar).  Although this might not be
very elegant, I find it convenient (use C++'s or R's, depending on which
one fits my problem better ---in particular, many distributions are not
readily available from C++). In C++ I tend to use std::mt19937, often with
a seed generated in R as

seed <- as.integer(round(runif(1, min = 0, max = 2^16)))

and passed to the C++ code.

It is my understanding that similar ideas (seeding C++'s RNG from R and
combining C++ with R's RNG) have been used before in much more complex
settings (e.g.,
http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2014-April/007510.html
and
http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2014-April/007512.html),
but I wonder if there are problems I cannot think of. A silly example
follows below.




Best,

R.


This is a silly example:

////////////////////////////////////////////////////////
#include <Rcpp.h>

using std::vector;
using namespace Rcpp;

double f0(vector<double> vec, std::mt19937& ran_gen) {
  shuffle(vec.begin(), vec.end(), ran_gen);
  return vec[0];
}

double f1() {
  RNGScope scope;
  double r = ::Rf_runif(0.0, 1.0);
  return r;
}

// [[Rcpp::export]]
double f3(int seed) {
  std::mt19937 ran_gen(seed);
  
  vector<double> vec(9);
  for(auto &v: vec ) {
    v = f1();
    Rcpp::Rcout << v << " ";
  }
  Rcpp::Rcout << std::endl;
  
  return f0(vec, ran_gen);
}

/*** R
f4 <- function(seed = NULL) {
  if(is.null(seed))
      seed <- as.integer(round(runif(1, min = 0, max = 2^16)))
  return(f3(seed))	
}
*/

////////////////////////////////////////////////////////


-- 
Ramon Diaz-Uriarte
Department of Biochemistry, Lab B-25
Facultad de Medicina
Universidad Autónoma de Madrid 
Arzobispo Morcillo, 4
28029 Madrid
Spain

Phone: +34-91-497-2412

Email: rdiaz02 at gmail.com
       ramon.diaz at iib.uam.es

http://ligarto.org/rdiaz


More information about the Rcpp-devel mailing list