Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
What happens at the very beginning of the loop:
for( init ; ; ){
}
Logical condition to control if the loop continues
for( ; condition ; ){
}
Executed at the end of each iteration
for( ; ; increment ){
}
Executed at each iteration. What the loop does.
for( ; ; ){
body
}
for (int i=0; i<n; i++ ){
// some code using i
}
for (int i=0; ; ){
}
for (int i=0; i<n; ){
}
for (int i=0; i<n; i++){
}
// [[Rcpp::export]]
int nfirst( int n ){
if( n < 0 ) {
stop( "n must be positive, I see n=%d", n ) ;
}
int result = 0 ;
for( int i=0; i<n; i++){
result = result + (i+1) ;
}
return result ;
}
// [[Rcpp::export]]
int nfirst( int n ){
if( n < 0 ) {
stop( "n must be positive, I see n=%d", n ) ;
}
int result = 0 ;
for( int i=0; i<n; i++){
if( i == 13 ){
Rprintf( "I cannot handle that, I am superstitious" ) ;
break ;
}
result = result + (i+1) ;
}
return result ;
}
Finding $\sqrt{S}$ is the same as finding the root of $f(x) = x^2 - S$
Leading to the iterative expression:
$$ x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} = x_n - \frac{x^2_n - S}{2 x_n} = \frac{1}{2} \left( x_n + \frac{S}{x_n} \right) $$
Algorithm:
$$ x_{n+1} = \frac{1}{2} \left( x_n + \frac{S}{x_n} \right) $$
translates to the pseudo code
int n = ... // number of iterations
double res = ... // initialization
for( int i=0; i<n; i++){
// update the value of res
// i.e. calculate x_{n+1} given x_{n}
res = ( res + S / res ) / 2.0 ;
}
return res ;
Optimizing R Code with Rcpp