我认为这里的问题是与算法的工作原理有点混淆。
为了从您的分布中生成单个值(X = 1,2,3,4 其中 P(X = 1) = .2, P(X = 2) = .15 , P(X = 3) = .25, P(X = 4) = .4),我们需要遵循算法的步骤。假设我们选择c = .4/.25:
1.从Y~UD(1,4)生成y。
2.从U~U(0,1)生成u。
3.检查是否u≤f(y)/cg(y)。如果它是,定义x = y,你就完成了!如果不是,请返回第 1 步。
在您提供的代码中,您从未真正生成 y 变量。这是一个应该为您工作的功能!希望我的 cmets 解释得足够清楚!
accRej <- function(){
#The probabilities for generating a r.v. from X
probX <- c(.2,.15,.25,.4)
#The Value for c
c <- .4/.25
#x is a placeholder for our final value of x
#and i is a counter variable which will allow us to stop the loop when we complete step 3
x <- numeric(1)
i <- 1
#Now, start the loop!
while(i <= 1){
#Step 1, get y
y <- sample(1:4,1)
#Step 2, get u
u <- runif(1)
#Step 3, check to see if the inequality holds
#If it does, assign y to x and add 1 to i (making it 2) to stop the while loop
#If not, do nothing and try again!
if(u <= probX[y]/c*.25){
x[i] <- y
i <- i+1
}
}
#Return our value of x
return(x)
}
注意这段代码中probX[i] 等于我们算法中的 f(y),并且由于 Y~UD(1,4),.25 = g(y ) 总是。希望这会有所帮助!
另外,这里是使用此方法生成n 随机变量的代码。基本上和上面一样,只是有一个选项可以把 1 改成n。
accRej <- function(n){
#The probabilities for generating a r.v. from X
probX <- c(.2,.15,.25,.4)
#The Value for c
c <- .4/.25
#x is a placeholder for our final value of x
#and i is a counter variable which will allow us to stop the loop when we complete step 3
x <- numeric(n)
i <- 1
#Now, start the loop!
while(i <= n){
#Step 1, get y
y <- sample(1:4,1)
#Step 2, get u
u <- runif(1)
#Step 3, check to see if the inequality holds
#If it does, assign y to x and add 1 to i
#If not, do nothing and try again!
if(u <= probX[y]/c*.25){
x[i] <- y
i <- i+1
}
}
#Return our value of x
return(x)
}