IniziaInizia 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
}

Questo esercizio fa parte del corso

Optimizing R Code with Rcpp

Visualizza il corso

Istruzioni dell'esercizio

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

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

#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)
*/
Modifica ed esegui il codice