简体   繁体   English

通过R中的自定义分布进行仿真

[英]Simulation from a customised distribution in R

Does anyone know how to simulate random variables from the following probability density function (pdf): 有谁知道如何根据以下概率密度函数(pdf)模拟随机变量:

在此处输入图片说明

where g(x) is the pdf for standard normal distribution N(0,1). 其中g(x)是标准正态分布N(0,1)的pdf。 I understand that simulating random variables from customised distribution involves finding the cumulative density function and using the uniform distribution (as there were similar questions on this topic in this platform also). 我了解从定制的分布中模拟随机变量涉及找到累积密度函数并使用均匀分布(因为在此平台上,该主题也存在类似的问题)。 However, the pdf I have here looks a bit more complicated than the other examples I came across before. 但是,我在这里看到的pdf看起来比我之前遇到的其他示例要复杂一些。 For example, I would imagine that finding the cumulative density function (need to integrate) is not so straight forward. 例如,我可以想象找到累积密度函数(需要积分)并不是那么简单。 Can anyone give me advice on how to solve this? 谁能给我建议如何解决这个问题? Or is there another simpler method to simulate from the above distribution? 还是有另一个更简单的方法可以根据上述分布进行模拟? Look forward to your advice. 期待您的建议。 Thanks! 谢谢!

You might try a Markov chain Monte Carlo approach such as the Metropolis-Hastings Algorithm. 您可以尝试使用Markov链蒙特卡罗方法,例如Metropolis-Hastings算法。 https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm

Doesn't this work? 这不行吗?

special <- function(x) {
               if (x <= -1) {
                  val <- dnorm(x) / (1+exp(-x-1))
               } else if ((x > -1) & (x < 1)) {
                  val <- dnorm(x) / 2
               } else {
                  val <- dnorm(x) / (1+exp(-x+1))
               }
               return(val)
           }

special(-2)
[1] 0.01452041

special(-0.5)
[1] 0.1760327

You can do this using sample ... 您可以使用sample执行此操作...

#define some x values
x <- seq(-5, 5, 0.001)
#define the pdf as above
f <- function(x) {
  if (x <= -1) {
    y <- dnorm(x)/(1+exp(-x-1))
  } else if (x >= 1) {
    y <- dnorm(x)/(1+exp(-x+1))
  } else {
    y <- dnorm(x)/2
  }
  return(y)
}
#calculate values of pdf for all x
fx <- f(x)
#create sample using these probabilities
samp <- sample(x, size=10000, replace=TRUE, prob=fx)

hist(samp, breaks=50)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM