我需要写一个以下方法的函数:
拒绝法(均匀包络):
假设fx仅在[a,b]上非零,并且fx≤k。
假设fx仅在[a,b]上非零,并且fx≤k。
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]).
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)
while(FALSE)
,这样我就可以进入该循环。 - user 31466while(TRUE)
看作是while(TRUE==TRUE)
,也就是说,无论如何都要继续执行。 - blmoorerepeat
,这可能是while(TRUE)
的更清晰版本(尽管老实说它似乎很少使用)。 - Kevin Ushey