[Rcpp-devel] RNGScope, importing function, and if-else statement

Marie Auger-Methe marie.augermethe at gmail.com
Sun Apr 15 20:01:30 CEST 2012


I want to use a random generator that is not available in the Rcpp: rvm 
from R's CircStats package and I want the number generated to be the 
same as the equivalent function in R. Importing the function within a 
Rcpp inline function works fine except if you have an if-else statement. 
The strange thing is that it works as long at the if-statement is TRUE, 
and then it doens't work anymore and some numbers are repeated but not 
in the same order.

Here is an example:


ft <- '
   Rcpp::NumericVector xc(clone(x));
   Rcpp::Function vmc(vm);
   int n = xc.size();
   NumericVector y(n);

   RNGScope Scope;

   for(int j=0; j<n; j++){
     if(xc[j] == 0){
       y[j] = as<double>(runif(1,0,2*PI));
       y[j] = as<double>(vmc(1,0,1));

   return y;'

ftt <- cxxfunction(signature( x ="numeric", vm = "function"),
             body = ft, plugin = "Rcpp")

ftr <- function(x){
     n <- length(x)
     y <- numeric(n)
     for(i in 1:n){
           if(x[i] == 0){
             y[i] = runif(1,0,2*pi)
             y[i] = rvm(1, 0, 1)

x <- c(0,0,0,1,1,1,0,0,0)

r1 <- ftt(x,rvm)
r2 <- ftr(x)

Any idea what my be causing the difference between R and Rcpp? Many 
thanks in advance!


More information about the Rcpp-devel mailing list