使用逆采样从分布函数生成随机变量 [英] Generate random variables from a distribution function using inverse sampling
问题描述
我有一个特定的密度函数,我想知道密度函数的表达式以生成随机变量.
I have a specific density function and I want to generate random variables knowing the expression of the density function.
例如,密度函数为:
df=function(x) { - ((-a1/a2)*exp((x-a3)/a2))/(1+exp((x-a3)/a2))^2 }
我想从这个表达式中生成1000个具有相同分布的随机元素.
From this expression I want to generate 1000 random elements with the same distribution.
我知道我应该使用逆采样方法.为此,我使用PDF的CDF函数,其计算如下:
I know I should use the inverse sampling method. For this, I use the CDF function of my PDF which is calculated as follows:
cdf=function(x) { 1 - a1/(1+exp((x-a3)/a2))
这个想法是生成均匀分布的样本,然后使用我的CDF函数将其映射以获得逆映射.像这样:
The idea is to generate uniformly distributed samples and then map them with my CDF functions to get an inverse mapping. Something like this:
random.generator<-function(n) sapply(runif(n),cdf)
,然后使用所需数量的随机变量来调用它来生成.
and then call it with the desired number of random variables to generate.
random.generator(1000)
这种方法正确吗?
推荐答案
第一步是获取cdf函数的逆函数,在这种情况下,可以通过简单的算术来完成:
The first step is to take the inverse of your cdf function, which in this case can be done with simple arithmetic:
invcdf <- function(y) a2 * log(a1/(1-y) - 1) + a3
现在,您要使用标准均匀分布的随机变量调用逆CDF进行采样:
Now you want to call the inverse cdf with standard uniformly distributed random variables to sample:
set.seed(144)
a1 <- 1 ; a2 <- 2 ; a3 <- 3
invcdf(runif(10))
# [1] -2.913663 4.761196 4.955712 3.007925 1.472119 4.138772 -3.568288
# [8] 4.973643 -1.949684 6.061130
这是10000个模拟值的直方图:
This is a histogram of 10000 simulated values:
hist(invcdf(runif(10000)))
这是pdf的图:
x <- seq(-20, 20, by=.01)
plot(x, df(x))
这篇关于使用逆采样从分布函数生成随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!