Doing mathematics with R: Control structures
Conditional repetition
Often in an algorithm, a series of commands must be repeated: this can be a predetermined number of times ( restricted repetition) or depend on a condition (conditional repetition). We will encounting both forms of repetition, but we will begin with the second.
The general form of a conditional repetition (while
instruction) is shown below. Read the explanation for detailed information:
Conditional repetition
while (condition) {
indented instructions if the condition is met
}
> x <- 1.0 > y <- x/2 + 1/x > n <- 0 > while (abs(y-x)>0) { + x <- y + y <- x/2 + 1/x + n <- n + 1 + } > io <- sprintf("y = %.15f after %d steps\n", y, n) > cat(io) y = 1.414213562373095 after 5 steps
In the form of a conditional repetition shown, the evaluation of the condition takes place at the beginning of the iteration loop: this is called a pre-checked loop. An alternative is to first execute a series of instructions and then check a condition. This is called a post-checked loop. It works like "perform operations until a condition is met". You can simulate a post-checked loop with a while
instruction. The example above could then look as follows (note that now the counting variable n ends at 6, instead of 5 in the above code):
> x <- 1.0 > n <- 0 > not_ready <- TRUE > while (not_ready) { + y <- x/2 + 1/x + n <- n + 1 + if (abs(x-y) == 0) { + not_ready <- FALSE + } else { + x <- y + } + } > io <- sprintf("y = %.15f after %d steps\n", y, n) > cat(io) y = 1.414213562373095 after 6 steps
The break
instruction also allows you to jump right out of the while
loop and continue with the instructions that follow. In the example below, we have modified the stop condition so that it is computationally safer, i.e., cannot result in an infinite repetition.
> x <- 1.0 > n <- 0 > epsilon <- 10^(-10) > while (TRUE) { + y <- x/2 + 1/x + n <- n + 1 + if (abs(x-y) < epsilon) { + break + } else { + x <- y + } + } > io <- sprintf("y = %.10f after %d steps\n", y, n) > cat(io) y = 1.4142135624 after 5 steps