用R语言写一段接受拒绝抽样方法的代码
时间: 2023-05-15 18:07:06 浏览: 127
以下是用R语言编写的接受拒绝抽样方法的代码:
```
# 定义目标分布密度函数
target_density <- function(x) {
return(0.8 * dnorm(x, mean = -2, sd = 1) + 0.2 * dnorm(x, mean = 2, sd = 1))
}
# 定义建议分布密度函数
proposal_density <- function(x) {
return(dnorm(x, mean = 0, sd = 2))
}
# 定义接受拒绝抽样函数
accept_reject_sampling <- function(target_density, proposal_density, n_samples) {
samples <- numeric(n_samples)
i <- 1
while (i <= n_samples) {
x <- rnorm(1, mean = 0, sd = 2)
u <- runif(1, min = 0, max = 1)
if (u < target_density(x) / (2 * proposal_density(x))) {
samples[i] <- x
i <- i + 1
}
}
return(samples)
}
# 生成1000个样本
samples <- accept_reject_sampling(target_density, proposal_density, 1000)
# 绘制样本分布图
hist(samples, breaks = 30, freq = FALSE, main = "Accept-Reject Sampling", xlab = "x")
curve(target_density, add = TRUE, col = "red", lwd = 2)
curve(proposal_density, add = TRUE, col = "blue", lwd = 2)
```
这段代码实现了接受拒绝抽样方法,用于从目标分布中生成样本。其中,目标分布由`target_density`函数定义,建议分布由`proposal_density`函数定义,`accept_reject_sampling`函数实现了接受拒绝抽样的过程,最终生成1000个样本并绘制样本分布图。
阅读全文