for 循环

用 Rcpp 优化 R 代码

Romain François

Consulting Datactive, ThinkR

C++ for 循环的 4 个部分

  • 初始化
  • 继续条件
  • 递增
  • 循环体
用 Rcpp 优化 R 代码

for 循环——初始化

循环一开始发生什么:

for( init ;  ;  ){

}
用 Rcpp 优化 R 代码

for 循环——继续条件

用于控制循环是否继续的逻辑条件

for(  ; condition ;  ){

}
用 Rcpp 优化 R 代码

for 循环——递增

每次迭代结束时执行

for(  ;  ; increment ){

}
用 Rcpp 优化 R 代码

for 循环——循环体

每次迭代执行。即循环要做的事。

for(  ;  ;  ){
    body
}
用 Rcpp 优化 R 代码

典型的 for 循环

for (int i=0; i<n; i++ ){
    // some code using i
}
用 Rcpp 优化 R 代码

典型的 for 循环

for (int i=0; ; ){

}
用 Rcpp 优化 R 代码

典型的 for 循环

for (int i=0; i<n; ){

}
用 Rcpp 优化 R 代码

典型的 for 循环

for (int i=0; i<n; i++){

}
用 Rcpp 优化 R 代码

示例:前 n 个整数之和

// [[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 优化 R 代码

跳出 for 循环

// [[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 ;
}
用 Rcpp 优化 R 代码

牛顿迭代法求平方根

求 $\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_0$
  • 按上式更新 $x$ 若干次
用 Rcpp 优化 R 代码

C++ 中的牛顿法

$$ 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 代码

Passons à la pratique !

用 Rcpp 优化 R 代码

Preparing Video For Download...