R,while(TRUE)是如何工作的?

8
我需要写一个以下方法的函数: 拒绝法(均匀包络)
假设fx仅在[a,b]上非零,并且fx≤k。
  1. Generate X ∼ U(a, b) and Y ∼ U(0, k) independent of X (so P = (X, Y ) is uniformly distributed over the rectangle [a, b] × [0, k]).

  2. If Y < fx(x) then return X, otherwise go back to step 1.

    rejectionK <- function(fx, a, b, K) {
        # simulates from the pdf fx using the rejection algorithm
        # assumes fx is 0 outside [a, b] and bounded by K
        # note that we exit the infinite loop using the return statement
    
        while (TRUE) {
          x <- runif(1, a, b)
          y <- runif(1, 0, K)
          if (y < fx(x)) return(x)
       }
    }
    

我不明白为什么在 while (TRUE) 中使用 TRUE?这与 IT 技术有关。

如果(y < fx(x))不成立,则该方法建议再次重复循环以重新生成均匀数。 (y < fx(x)) 不成立 = FALSE。那么为什么条件不是 while (FALSE)

那么,基于什么情况会进入 while 循环呢?也就是说,我已经习惯了这个。

   a=5 
   while(a<7){
      a=a+1
   }

在写条件语句之前,我定义了一个变量a<7。

但是在while (TRUE)中,哪个语句是真的?

另外:

你可以运行这些代码。

  rejectionK <- function(fx, a, b, K) {
        # simulates from the pdf fx using the rejection algorithm
        # assumes fx is 0 outside [a, b] and bounded by K
        # note that we exit the infinite loop using the return statement

        while (TRUE) {
          x <- runif(1, a, b)
          y <- runif(1, 0, K)
          cat("y=",y,"fx=",fx(x),"",y < fx(x),"\n")
          if (y < fx(x)) return(x)
       }
    }

  fx<-function(x){
     # triangular density
     if ((0<x) && (x<1)) {
       return(x)
     } else if ((1<x) && (x<2)) {
       return(2-x)
     } else {
       return(0)
     }
 }

 set.seed(123)
 rejectionK(fx, 0, 2, 1)
2个回答

16

这是一个无限循环。只要条件评估为TRUE,就会执行表达式,而它将永远评估为TRUE。但是,在表达式中有一个return语句,当它被调用时(例如,如果y < fx(x)),它会退出函数并停止循环。

这里有一个更简单的例子:

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"

这个函数被调用时会发生什么?

  1. i设置为1。
  2. 测试while循环的条件。由于它是TRUE,因此评估其表达式。
  3. 测试if结构的条件。由于它是FALSE,所以评估else表达式并打印i的值。
  4. 增加i的值1。
  5. 重复步骤3和4。
  6. i达到4的值时,if结构的条件为TRUE,并且return("stopped")被评估。这将停止整个函数并返回值"stopped"。

抱歉,我还没有理解。哪个语句需要是TRUE?i>n还是i<n? - user 31466
1
抱歉,我不理解你的问题。 - Roland
当i = 1时,为什么会进入循环?1不大于3,因此为FALSE,我需要重复循环直到返回“stopped”。 因此,为什么条件不是while(FALSE),这样我就可以进入该循环。 - user 31466
1
你没有理解重点,把while(TRUE)看作是while(TRUE==TRUE),也就是说,无论如何都要继续执行。 - blmoore
顺便提一下,R实际上有关键字repeat,这可能是while(TRUE)的更清晰版本(尽管老实说它似乎很少使用)。 - Kevin Ushey

4
在while循环内部,如果我们有返回真或假的语句...它将按照相应的方式工作。
例如:检查列表是否为循环。在这里,循环是无限的,因为while(true)总是为真,但我们可以通过使用返回语句有时打破循环。
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;
}

使用"break"关键字。 - caner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接