如何使用概率函数最好地模拟任意单变量随机变量? [英] How do I best simulate an arbitrary univariate random variate using its probability function?
本文介绍了如何使用概率函数最好地模拟任意单变量随机变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 R 中,如果只有概率密度函数可用,模拟任意单变量随机变量的最佳方法是什么?
In R, what's the best way to simulate an arbitrary univariate random variate if only its probability density function is available?
推荐答案
当您只给定密度时,这是逆 cdf 方法的(缓慢)实现.
Here is a (slow) implementation of the inverse cdf method when you are only given a density.
den<-dnorm #replace with your own density
#calculates the cdf by numerical integration
cdf<-function(x) integrate(den,-Inf,x)[[1]]
#inverts the cdf
inverse.cdf<-function(x,cdf,starting.value=0){
lower.found<-FALSE
lower<-starting.value
while(!lower.found){
if(cdf(lower)>=(x-.000001))
lower<-lower-(lower-starting.value)^2-1
else
lower.found<-TRUE
}
upper.found<-FALSE
upper<-starting.value
while(!upper.found){
if(cdf(upper)<=(x+.000001))
upper<-upper+(upper-starting.value)^2+1
else
upper.found<-TRUE
}
uniroot(function(y) cdf(y)-x,c(lower,upper))$root
}
#generates 1000 random variables of distribution 'den'
vars<-apply(matrix(runif(1000)),1,function(x) inverse.cdf(x,cdf))
hist(vars)
这篇关于如何使用概率函数最好地模拟任意单变量随机变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文