Generování náhodných čísel

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Generování jednotlivých náhodných čísel

// 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 ) ;

// ...
Optimizing R Code with Rcpp

Generování vektorů

Generátory náhodných čísel v prostoru jmen Rcpp::.

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

Alternativa pomocí skalárních verzí z R::

// same as 
NumericVector x(10) ; 
for(int i=0; i<10; i++){
    x[i] = R::rnorm(0, 2) ;
}
Optimizing R Code with Rcpp

Optimizing R Code with Rcpp

Metoda odmítání

// 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 ;    
}
Optimizing R Code with Rcpp

Optimizing R Code with Rcpp
  • Výběr komponenty směsi pomocí vah
int component( NumericVector weights, double total_weight ){
    // return the index of the selected component}
  • Generování čísla pomocí parametrů vybrané komponenty
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 ;
}
Optimizing R Code with Rcpp

Pojďme si procvičit!

Optimizing R Code with Rcpp

Preparing Video For Download...