【发布时间】:2013-09-27 08:22:13
【问题描述】:
我要写一个如下方法的函数:
拒绝方法(统一包络):
假设 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) } }
我一直不明白为什么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