0

Let me provide some context cause I am not sure if have over or under simplified the problem. There exists parallel workers, that preform a series of bootstraps, each worker has its own RNG, std::mt19937 mersene twister. I would like add some randomization to each Nelder-Mead Simplex that optimizes the bootstraps. The question is how to pass the RNG from the worker to a function. The example below is without parallelization, as I don't think its related to my problem.

// [[Rcpp::depends(RcppArmadillo)]
// [[Rcpp::plugins(cpp11)]]
#include <RcppArmadillo.h>
#include <random>

using namespace arma;

//typedef std::mt19937 rng_engine;

template< class rng_engine >

arma::rowvec internal(rng_engine &engine, int counts){

  arma::rowvec output(10);
    // This is wrong
  output = std::unif_rand<double>(0.0, 1.0, 10, engine);
  return output;
}

// [[Rcpp::export]]
arma::rowvec example( int counts){

  rng_engine engine(1);
  engine.seed(seed);

  return internal( &engine, counts);
}

/*** R
example( 10 , 1)
*/
skatz
  • 115
  • 7

1 Answers1

0

Ok this works, haven't checked it yet to see if it is thread-safe. Also seems like there should be a way of doing this without the for loop.

// [[Rcpp::depends(RcppArmadillo)]

// [[Rcpp::plugins(cpp11)]]
#include <RcppArmadillo.h>
#include <random>

using namespace arma;


arma::rowvec internal(std::mt19937& engine, int counts){


  arma::rowvec output(counts, arma::fill::zeros);
  std::uniform_real_distribution<double> dist(0, 1);
  for(int f = 0; f< counts; f++){
    output[f] = dist(engine);
  }

  return output;
}

// [[Rcpp::export]]
arma::rowvec example( int counts, int seed){

  std::mt19937 engine(1);
  engine.seed(seed);

  return internal( engine, counts);
}

/*** R
example( 10 , 1)
*/
skatz
  • 115
  • 7