開始使用免費開始

用 while 迴圈計算平方根

while 迴圈會持續重複執行,直到條件不再成立。C++ 的 while 迴圈語法和 R 相同。

while(condition) {
  // Do something
}

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

設定 while 迴圈,讓它在 is_good_enough 為 false 時持續迭代。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

#include 
using namespace Rcpp;

// [[Rcpp::export]]
double sqrt_approx(double value, double threshold) {
    double x = 1.0;
    double previous = x;
    bool is_good_enough = false;
    
    // Specify the while loop
    ___(___) {
        previous = x;
        x = (x + value / x) / 2.0;
        is_good_enough = fabs(x - previous) < threshold;
    }
    
    return x ;
}

/*** R
sqrt_approx(2, 0.00001)
*/
編輯並執行程式碼