β分布R代码的接受拒绝

时间:2017-11-13 16:22:40

标签: r statistical-sampling

我正在使用接受 - 拒绝方法进行β分布,g(x)=1,0≤x≤1。 功能是: f(x)= 100x ^ 3(1-x)^ 2.

我想创建一个算法来从这个密度函数生成数据。

如何在k = 1000次重复(n = 1000)的情况下估计P(0≤X≤0.8)?我怎样才能在R中解决这个问题?

我已经拥有:

beta.rejection <- function(f, c, g, n) {
naccepts <- 0
result.sample <- rep(NA, n)

  while (naccepts < n) {
    y <- runif(1, 0, 0.8)
    u <- runif(1, 0, 0.8)

    if ( u <= f(y) / (c*g(y)) ) {
      naccepts <- naccepts + 1
      result.sample[n.accepts] = y
    }
  }

  result.sample
}

f <- function(x) 100*(x^3)*(1-x)^2
g <- function(x) x/x
c <- 2

result <- beta.rejection(f, c, g, 10000)

for (i in 1:1000){ # k = 1000 reps
  result[i] <- result[i] / n
}

print(mean(result))

1 个答案:

答案 0 :(得分:1)

你很接近,但有一些问题:

1)错误nacceptsn.accepts

2)如果您不打算在g中进行硬连接,那么您不应该在runif()中硬连接作为生成随机变量的函数,该随机变量按{{1}分布}}。函数g(为什么rejection中的硬连线?)也应该传递一个能够生成适当随机变量的函数。

3)beta应该来自u而不是[0,1][0,0.8]应该不参与值的生成,只是它们的解释。

4)0.8需要是c的上限。 2太小了。为什么不采用f(y)/g(y)的导数来找到它的最大值? 3.5作品。另外 - f不是R中变量的好名称(因为函数c)。为什么不称它为c()

进行这些更改会产生:

M

典型输出:rejection <- function(f, M, g, rg,n) { naccepts <- 0 result.sample <- rep(NA, n) while (naccepts < n) { y <- rg(1) u <- runif(1) if ( u <= f(y) / (M*g(y)) ) { naccepts <- naccepts + 1 result.sample[naccepts] = y } } result.sample } f <- function(x) 100*(x^3)*(1-x)^2 g <- function(x) 1 rg <- runif M <- 3.5 #upper bound on f (via basic calculus) result <- rejection(f, M, g,rg, 10000) print(length(result[result <= 0.8])/10000)

您还可以制作0.9016的密度直方图,并将其与理论β分布进行比较:

result

比赛非常好:

enter image description here