НачатьНачать бесплатно

Breaking out of a for loop

Sometimes you may wish to exit a loop before you've completed all the iterations. For example, your code may succeed in its task before all possibilities have been tried. The break keyword can be used to break out of a loop early.

The code pattern looks like this:

for(int i = 0; i < n; i++) {
  // Do something

  // Test for exiting early
  if(breakout_condition) break;

  // Otherwise carry on as usual
}

Here you'll rework the previous example so that the loop stops when the value does not change too much (based on a threshold). The function has been modified so that it returns a List (you will learn about Lists in the next chapter), enabling you to see the approximation at each iteration.

This modified sqrt_approx() function returns both the square root and the number of iterations it took to achieve this result based on the threshold.

Это упражнение является частью курса

Optimizing R Code with Rcpp

Посмотреть курс

Инструкции к упражнению

Add a break condition that triggers if the solution is good enough (based on the variable is_good_enough).

Интерактивное практическое упражнение

Попробуйте выполнить это упражнение, дополнив этот пример кода.

#include 
using namespace Rcpp;

// [[Rcpp::export]]
List sqrt_approx(double value, int n, double threshold) {
    double x = 1.0;
    double previous = x;
    bool is_good_enough = false;
    int i;
    for(i = 0; i < n; i++) {
        previous = x;
        x = (x + value / x) / 2.0;
        is_good_enough = fabs(previous - x) < threshold;
        
        // If the solution is good enough, then "break"
        ___(___) ___;
    }
    return List::create(_["i"] = i , _["x"] = x);
}

/*** R
sqrt_approx(2, 1000, 0.1)
*/
Редактировать и запускать код