R,while(TRUE)如何工作?

标签 r loops while-loop

我必须编写以下方法的功能:

拒收方法(均匀信封):

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

  • 生成独立于X的X〜U(a,b)和Y〜U(0,k)(因此P =
    (X,Y)均匀分布在矩形[a,b]×[0,k]上)。
  • 如果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)
       }
    }
    

  • 我不明白为什么TRUE中的这个while (TRUE)吗?

    如果(y while (FALSE)呢?

    同样,我将基于哪个基础进入while循环?也就是说,我已经习惯了
       a=5 
       while(a<7){
          a=a+1
       }
    

    在这里,我在写条件(a <7)之前定义了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)
    

    最佳答案

    这是一个无限循环。只要条件的计算结果为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"
    

    调用此函数会发生什么?
  • i设置为1。
  • 测试了while循环的条件。因为它是TRUE,所以它的表达式被求值。
  • 测试了if构造的条件。由于它是FALSE,因此对else表达式进行求值并打印i
  • i增加1。
  • 重复步骤3和4。
  • i达到值4时,if构造的条件为TRUE,并评估return("stopped")。这将停止整个功能并返回值“stopped”。
  • 关于R,while(TRUE)如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18942299/

    相关文章:

    java - 循环不执行多次

    r - 是否可以使用 rlang 构造赋值表达式?

    roxygen2 "Error: titlerequires a value"

    r - 你会如何在 R 中完成这个棘手的子集化?

    r - 提取字符串并填充到 r 中的其他列

    python - 如何让 python 读取 .txt 文件的每一行?

    java - while循环不会循环

    c - 无限 while 循环和 control-c

    loops - 尝试在批处理文件中查找 CPU 核心数量

    python - 调用第二个脚本并结束循环后变量不会保留(Python)