I have to write a function of the following method :
Rejection method (uniform envelope):
Suppose that fx is non-zero only on [a, b], and fx ≤ k.
It's an infinite loop. The expression is executed as long as the condition evaluates to TRUE
, which it will always do. However, in the expression there is a return
, which when called (e.g., if y < fx(x)
), breaks out of the function and thus stops the loop.
Here is a simpler example:
fun <- function(n) {
i <- 1
while (TRUE) {
if (i>n) return("stopped") else print(i)
i <- i+1
}
}
fun(3)
#[1] 1
#[1] 2
#[1] 3
#[1] "stopped"
What happens when this function is called?
i
is set to 1.while
loop is tested. Because it is TRUE
, it's expression is evaluated. if
construct is tested. Since it is FALSE
the else
expression is evaluated and i
is printed.i
is increased by 1.i
reaches the value of 4, the condition of the if
construct is TRUE
and return("stopped")
is evaluated. This stops the whole function and returns the value "stopped".