【问题标题】:R, How does while (TRUE) work?R,while (TRUE) 是如何工作的?
【发布时间】:2013-09-27 08:22:13
【问题描述】:

我要写一个如下方法的函数:

拒绝方法(统一包络)

假设 fx 仅在 [a, b] 和 fx ≤ k 上非零。

  1. 生成独立于 X 的 X ∼ U(a, b) 和 Y ∼ U(0, k)(所以 P = (X, Y ) 在矩形 [a, b] × [0, k] 上均匀分布。

  2. 如果 Y

    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

如果 (y while (FALSE)?

我将再次进入 while 循环的基础是什么?也就是说,我已经习惯了这个

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

这里我在写条件(a

但是在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)

【问题讨论】:

    标签: r loops while-loop


    【解决方案1】:

    这是一个无限循环。只要条件的计算结果为TRUE,就会执行表达式,它总是会这样做。但是,表达式中有一个return,当调用它时(例如,如果y &lt; 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")。这将停止整个函数并返回值“停止”。

    【讨论】:

    • 我很抱歉。我还没弄明白。哪个陈述必须为真? i>n 或 i
    • 对不起,我不明白你的问题。
    • 当 i=1 为什么我会进入循环? 1 不大于 3,所以这是 FALSE,我需要重复循环,直到它返回“停止”。因此为什么不是while(FALSE) 的条件让我可以进入循环。
    • 你没有抓住重点,把while(TRUE)想象成while(TRUE==TRUE),即不管怎样都继续
    • 仅供参考,R 实际上有关键字repeat,这可能是while(TRUE) 的更清晰版本(虽然老实说它似乎很少使用)
    【解决方案2】:

    在while循环中,如果我们有true或false的return语句..它会相应地工作..

    例子:检查一个列表是否是循环的..

    这里的循环是无限的,因为 while (true) 总是为真,但我们有时可以通过使用 return 语句来中断。

    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的使用
    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 2020-04-08
    • 2021-10-30
    相关资源
    最近更新 更多