0

I want to generate a random vector, all the elements in the vector are from a beta distribution. Since there is no such function in armadillo. My current solution is to use rbeta function(ftest1 & ftest2). But is seems super time-consuming compare with the gamma function(ftest3) in armadillo. The code is following

// [[Rcpp::export]]
NumericVector ftest1(int N){
    NumericVector sam=Rcpp::rbeta(N,2.0,1.0);
    return(sam);
}
// [[Rcpp::export]] 
arma::vec ftest2(int N){
   arma::vec sam(N);
   for(int i=0;}i<N;i++){
   sam(i)=R::rbeta(2.0,1.0);
  }
return(sam);
}

// [[Rcpp::export]]
arma::vec ftest3(int N){
   arma::vec sam=arma::randg<vec>(N,distr_param(2.0,1.0));
   return(sam);}

The benchmark is following

library(microbenchmark)
N=1e4
microbenchmark(ftest1(N),ftest2(N),ftest3(N))
Unit: microseconds
  expr      min        lq     mean   median        uq      max neval
 ftest1(N) 1387.828 1405.5515 1433.774 1410.711 1420.2070 2841.565   100
 ftest2(N) 1413.557 1426.2355 1449.731 1433.162 1440.3870 2310.573   100
 ftest3(N)  166.255  177.0765  291.415  178.788  180.9045 8281.423   100

Does it possible to reduce the time cost for sampling from beta distribution?

Xia.Song
  • 416
  • 3
  • 15
  • 4
    I think you are comparing incomparables: a gamma generator from the Armadillo namespace, and a beta generator from the Rcpp namespace. For work with/from R, I would (generally) stick with the R generators. – Dirk Eddelbuettel Mar 31 '20 at 14:30
  • 2
    To add to @Dirk’s point: For the gamma distribution Armadillo uses a class from the C++ standard library. These distribution functions are implementation defined, so one might get different results for the same seed using different compilers/libraries. – Ralf Stubner Mar 31 '20 at 18:08

0 Answers0