MulaiMulai sekarang secara gratis

Calculating square roots with a while loop

While loops keep running iterations until a condition is no longer met. The syntax for a C++ while loop is the same is in R.

while(condition) {
  // Do something
}

Latihan ini adalah bagian dari kursus

Optimizing R Code with Rcpp

Lihat Kursus

Petunjuk latihan

Specify the while loop, so it keeps iterating while the value of is_good_enough is false.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

#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)
*/
Edit dan Jalankan Kode