Vectorised Rcpp random binomial draws

前端 未结 2 1368
感情败类
感情败类 2020-12-17 06:00

This is a follow-on question from this one: Generating same random variable in Rcpp and R

I\'m trying to speed up a vectorised call to rbinom of this form:



        
2条回答
  •  轮回少年
    2020-12-17 06:18

    Not a general solution, but I'm noticing that you set the size argument to 1 in your call to rbinom. If that's always the case, you can draw length(x) uniform values and then comparing to x. For instance:

     set.seed(123)
     #create the values
     x<-runif(1000000)
     system.time(res<-rbinom(length(x),1 ,x))   
     # user  system elapsed 
     #0.068   0.000   0.070
     system.time(res2<-as.integer(runif(length(x))

    Not a huge gain, but maybe you can save some little time if you call runif from C++, avoiding some overhead.

提交回复
热议问题