我的目标PDF如下:
和 0 其他地方。
我的提案PDF是
我的代码如下:
f= function(x) {
if (x >= 0 & x <= pi/2) {
return((4/pi^2)*x)
} else if (x > pi/2 & x <= pi) {
return(4/pi - (4/pi^2)*x)
} else {
return(0)
}
}
g = function(x) {
if (x >= pi/2 && x <= pi) {
return(sin(x)/2)
} else {
return(0)
}}
M <- max(f(x)/g(x))
rejection_sampling <- function(n) {
samples <- numeric(n)
i <- 1
while (i <= n) {
x <- runif(1, min = 0, max = pi)
u <- runif(1)
if (u <= f(x)/(M*g(x))) {
samples[i] <- x}
else{
i <- i + 1
}
return(samples)
}
samples <- rejection_sampling(1000)
hist(samples, breaks=50)
当我运行“样本”行时<- rejection_sampling(1000)", I get the error message
Error in if (u <= f(x)/(M * g(x))) { :
missing value where TRUE/FALSE needed
运行“M”行<- max(f(x)/g(x))" also gives me the error message
Error in if (x >= 0 & x <= pi/2) { : the condition has length > 1
因此,我无法绘制直方图。请帮我修复代码!