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 exercício faz parte do curso
Optimizing R Code with Rcpp
Instruções do exercício
Specify the while loop, so it keeps iterating while the value of is_good_enough
is false.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
#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)
*/