我必须编写以下方法的功能:
拒收方法(均匀信封):
假设fx仅在[a,b]上为非零,且fx≤k。
(X,Y)均匀分布在矩形[a,b]×[0,k]上)。
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循环?也就是说,我已经习惯了
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。i
达到值4时,if
构造的条件为TRUE
,并评估return("stopped")
。这将停止整个功能并返回值“stopped”。 关于R,while(TRUE)如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18942299/