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

Este ejercicio forma parte del curso

Optimizing R Code with Rcpp

Ver curso

Instrucciones del ejercicio

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

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

#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)
*/
Editar y ejecutar código