CommencerCommencer gratuitement

Do it again: do-while loop

The repeat loop in R is called a do while loop in C++. Compared to a while loop, it moves the condition to the end of the loop, so that the loop contents are guaranteed to be run at least once. The syntax is as follows:

do {
  // Do something
} while(condition);

Notice the semicolon after the while condition.

Cet exercice fait partie du cours

Optimizing R Code with Rcpp

Afficher le cours

Instructions

  • Initiate the loop with a do statement.
  • Specify the while condition, so the loop keeps iterating while the value of is_good_enough is false.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

#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;
    
    // Initiate do while loop
    ___ {
        previous = x;
        x = (x + value / x) / 2.0;
        is_good_enough = fabs(x - previous) < threshold;
    // Specify while condition
    } ___
    
    return x;
}

/*** R
sqrt_approx(2, 0.00001)
*/
Modifier et exécuter le code