R - 具有给定函数的逆累积分布法

R - Inverse cumulative distribution method with given function

我有一个给定的函数(我们称它为 f(x)),我使用 Monte Carlo 方法对其进行了规范化。我计算了概率密度函数,并通过积分得到了累积分布函数。

f = function(x) ...

plot(f,xlim = c(0, 5), ylim = c(0, 1),main="f(x)")

mc.integral = function(f, n.iter = 1000, interval){
  x = runif(n.iter, interval[1], interval[2])
  y = f(x)
  mean(y)*(interval[2] - interval[1])
}

MC = mc.integral(f, interval = c(0, 8))
print(MC)

densityFunction <- function(x){
  return ((f(x)/MC)) 
}

distributionFunction <- function(x){
  return  (integrate(densityFunction,0,x)$value)
}

vd <- Vectorize(distributionFunction)
plot(vd,xlim = c(0, 8), ylim = c(0, 1),ylab = "y",main="E(f(x))")

现在我的下一个任务是使用逆变换法/逆累积分布法生成样本并用Kolmogorov-Smirnov Test进行测试,但我不知道在R中应该怎么做

你能帮我一些忙吗?

那么,this thread向我们展示了如何使用逆变换方法生成样本:

sample <- vd(runif(1000))

> head(sample)
[1] 0.28737403 0.59295499 0.30814305 0.27998306 0.07601228 0.52753327

因此,可以通过以下方式生成 10 个不同的随机样本:

sample <- list()
for(i in 1:10){
  set.seed(i)
  sample[[i]] <- vd(runif(1000))
}

然后,在列表上循环 ks.test

lapply(sample, function(x) ks.test(x, pnorm))

将为您提供每个样本的测试与正态性的输出。明智地选择样本的大小,因为大多数正态性检验对于大样本很容易产生显着影响,即使差异很小(参考 here)。