[Rcpp-devel] RNGScope, importing function, and if-else statement
Dirk Eddelbuettel
edd at debian.org
Sun Apr 15 22:39:46 CEST 2012
Hi Marie,
On 15 April 2012 at 19:01, Marie Auger-Methe wrote:
| Hi,
|
| 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:
|
| suppressMessages(library(CircStats))
| suppressMessages(library(inline))
|
|
| 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));
| }else{
| 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)
| }else{
| y[i] = rvm(1, 0, 1)
| }
| }
| return(y)
| }
|
| x <- c(0,0,0,1,1,1,0,0,0)
|
| set.seed(9)
| r1 <- ftt(x,rvm)
| set.seed(9)
| r2 <- ftr(x)
| cbind(x,r1,r2)
|
| Any idea what my be causing the difference between R and Rcpp? Many
| thanks in advance!
I won't have a chance to disentangle this in detail, but could you possibly
just "reimplement" what rvm does using the Rcpp sugar functions?
That way you would be guaranteed the "nice" behaviour of properly replicating
RNG draws from R in C++.
Dirk
|
| Marie
|
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
--
R/Finance 2012 Conference on May 11 and 12, 2012 at UIC in Chicago, IL
See agenda, registration details and more at http://www.RinFinance.com
More information about the Rcpp-devel
mailing list