R, How does while (TRUE) work?

前端 未结 2 1739
长情又很酷
长情又很酷 2021-02-15 12:32

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.

相关标签:
2条回答
  • 2021-02-15 13:06

    Inside while loop, if we have return statement with true or false.. it will work accordingly..

    Example: To Check a list is circular or not..

    here the loop is infinite, because while (true) is true always, but we can break sometimes by using the return statement,.

    while(true)
    {
    if(!faster || !faster->next)
    return false;
    else
    if(faster==slower || faster->next=slower)
    {
    printf("the List is Circular\n");
    break;
    }
    else
    {
    slower = slower->next;
    faster = faster->next->next;
    }
    
    0 讨论(0)
  • 2021-02-15 13:13

    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?

    1. i is set to 1.
    2. The condition of the while loop is tested. Because it is TRUE, it's expression is evaluated.
    3. The condition of the if construct is tested. Since it is FALSE the else expression is evaluated and i is printed.
    4. i is increased by 1.
    5. Steps 3 and 4 are repeated.
    6. When 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".
    0 讨论(0)
提交回复
热议问题