随机数生成

用 Rcpp 优化 R 代码

Romain François

Consulting Datactive, ThinkR

生成单个随机数

// one number from a N(0,1)
double x = R::rnorm( 0, 1 ) ;

// one number from a U(-2,2)
double y = R::runif( -2, 2 ) ;

// ...
用 Rcpp 优化 R 代码

生成向量

Rcpp:: 命名空间中的随机数生成器。

NumericVector x = rnorm(10, 0, 2) ;
// same as this below
// because of using namespace Rcpp ;
// 
// NumericVector x = Rcpp::rnorm(10, 0, 2) ;

可选:使用 R:: 的标量版本

// same as 
NumericVector x(10) ; 
for(int i=0; i<10; i++){
    x[i] = R::rnorm(0, 2) ;
}
用 Rcpp 优化 R 代码

用 Rcpp 优化 R 代码

拒绝采样

// we generate n numbers
NumericVector x(n) ;

// fill the vector in a loop
for( int i=0; i<n; i++){
    // keep generating d until it gets positive
    double d  ;
    do {
        d = ... ;
    } while( d < 0 ) ;

    x[i] = d ;    
}
用 Rcpp 优化 R 代码

用 Rcpp 优化 R 代码
  • 按权重选择混合成分
int component( NumericVector weights, double total_weight ){
    // return the index of the selected component}
  • 用所选成分的参数生成数值
NumericVector rmix( int n, NumericVector weights, NumericVector means, 
                    NumericVector sds ){
    NumericVector res(n) ;    
    for( int i=0; i<n; i++){
        // find which component to use
        ...        
        // simulate using the mean and sd from the selected component
        ...    }    
    return res ;
}
用 Rcpp 优化 R 代码

开始练习!

用 Rcpp 优化 R 代码

Preparing Video For Download...