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
}
This exercise is part of the course
Optimizing R Code with Rcpp
Exercise instructions
Specify the while loop, so it keeps iterating while the value of is_good_enough
is false.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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;
// 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)
*/