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

Marie Auger-Methe marie.augermethe at gmail.com
Mon Apr 16 10:09:55 CEST 2012


Yes, there is something weird about the RNG. If you replace vmc by a 
function known to Rcpp such as rnorm this problem doesn't occur. If you 
create a function that uses only the imported vmc the problem doesn't 
occur either.  The problem resides in calling two functions, of which 
one is imported, since the same problem occur without the if-else statement:

suppressMessages(library(CircStats))
suppressMessages(library(inline))

ft <- '
   Rcpp::Function vmc(vm);
   Rcpp::NumericVector y(2);

   RNGScope Scope;

   y[0] = as<double>(runif(1,0,2*PI));
   y[1] = as<double>(vmc(1,0,1));

return y;'

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

ftr <- function(){
   y <- numeric(2)
     y[1] = runif(1,0,2*pi)
     y[2] = rvm(1, 0, 1)
   return(y)
}


set.seed(11)
r1 <- ftt(rvm)
set.seed(11)
r2 <- ftr()
cbind(r1,r2)

Marie

On 16/04/2012 6:11 AM, Davor Cubranic wrote:
> At Sun, 15 Apr 2012 19:01:30 +0100, Marie Auger-Methe wrote:
>> 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.
> In this example, it looks to me that the key is that as soon as you
> start using 'vmc', the numbers get out of order. If that's the case,
> then perhaps 'vmc' and 'runif' somehow both use the random seed, but
> RNGScope keeps track only of 'runif's?
>
> Davor



More information about the Rcpp-devel mailing list