3

我正在使用拒绝方法模拟数据,其中的密度函数由X给出f(x)= C * e^(x) for all x in [0,1]。我定义g(x) = 1C是其中的最大值f(x)等于1/(e-1)

我使用以下代码来模拟数据:

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

  while (naccepts < n) {
    y <- rg(1)
    u <- runif(1)

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

  result.sample
}

f <- function(x) ifelse(x>=0 & x<=1, (exp(x)), 0)
g <- function(x) 1
rg <- runif
C <-  1/(exp(1) -1)

result <- rejection(f, C, g,rg, 1000)

然后,我使用histogram将模拟数据与curve原始数据pdf进行比较

hist(result,freq = FALSE)
curve(f, 0, 1, add=TRUE)

但是结果的情节有点奇怪!情节就在这里,所以我正在寻找任何帮助来澄清我的工作中出了什么问题。

4

2 回答 2

0

你的最大值是错误的。对于 [0...1] 区间内的 exp(x),归一化 PDF 将是

f(x) = exp(x)/(exp(1) - 1)

因此 f(x) 的最大值是 exp(1)/(exp(1) - 1)

更新

好的,下面是关于拒绝采样的 wiki 文章的代码

sampleRej <- function(f, g, rg, M, n) { # rejection sampling following wiki
    naccepts <- 0
    result   <- rep(NA, n)

    while (naccepts < n) {
        y <- rg(1)
        u <- runif(1)

        if ( u <= f(y) / (M*g(y)) ) {
            naccepts <- naccepts + 1
            result[naccepts] = y
        }
    }

    result
}

g <- function(x) { # Normalized uniform distribution PDF
    1.0
}

f <- function(x) { # normalized sampling PDF
    exp(x)/(exp(1.0) - 1.0)
}

rg <- function(n) { # function to sample from g, which is uniform
    runif(n)
}


M <- exp(1.0)/(exp(1.0) - 1.0) # f(x) maximum value
q <- sampleRej(f, g, rg, M, 100000) # sample 100K points

# and plot everything together
curve(f, 0.0, 1.0)
hist(q, freq=FALSE, add=TRUE)

它会产生如下图,对我来说看起来不错

在此处输入图像描述

于 2020-02-21T20:13:03.837 回答
0

这显示了整个曲线和直方图:

curve(f, 0, 1)
hist(result,freq = FALSE, add=TRUE)

但当然,现在直方图在图中有点小......

于 2020-02-21T14:49:45.317 回答