用 Rcpp 优化 R 代码
Romain François
Consulting Datactive, ThinkR
循环一开始发生什么:
for( init ; ; ){
}
用于控制循环是否继续的逻辑条件
for( ; condition ; ){
}
每次迭代结束时执行
for( ; ; increment ){
}
每次迭代执行。即循环要做的事。
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 ;
}
求 $\sqrt{S}$ 等价于求 $f(x) = x^2 - S$ 的根。
得到迭代式:
$$ 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) $$
算法:
$$ x_{n+1} = \frac{1}{2} \left( x_n + \frac{S}{x_n} \right) $$
对应的伪代码:
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 ;
用 Rcpp 优化 R 代码