我尝试使用函数后面描述的逆cdf方法found here从R中的以下函数给出的给定分布中生成随机值
sigma=function(x){
rc=0.5
y=(x/rc) ;
C=(1/rc) ;
Fun = log(1+C)-( C/(1+C) ) ;
##### terms
a = 1/( y^2 - 1) ; b = 2/( sqrt(y^2 + 1 ) ) ; c = atan( sqrt((y - 1)/y+1) ) ;
ff = a*(1 - b*c) ;
##### My function
cst=2*pi
sigma1 = (ff)/(cst*(rc^2)*Fun) ## function to generate random values
# return(sigma1)
}
######## inverse CDF method from "found here" link
den<-sigma
#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)
然后出现以下错误:
Error in integrate(den, -Inf, x) : the integral is probably divergent
Called from: integrate(den, -Inf, x)
不幸的是,我无法理解我的功能在哪里出问题。但是我尝试了另外一种方法:(which can be found here)
library(distr)
p <- sigma # probability density function
dist <-AbscontDistribution(d=p) # signature for a dist with pdf ~ p
rdist <- r(dist) # function to create random variates from p
set.seed(1) # for reproduceable example
X <- rdist(1000) # sample from X ~ p
x <- seq(-10,10, .01)
hist(X, freq=F, breaks=50, xlim=c(-5,5))
lines(x,p(x),lty=2, col="red")
当我运行第dist <-AbscontDistribution(d=p)
行时,会显示以下错误:
Error in seq.default(from = low1, to = upp1, length = ngrid) :
'from' cannot be NA, NaN or infinite
Além disso: Warning message:
In sqrt((y - 1)/y + 1) : NaNs produzidos
我想知道是否有人可以帮助我解决这个问题,并指出一些真正有效的方法?
我为我的问题中的任何错误道歉。
如果我对自己的怀疑不是很清楚,那么我尝试做的事情与this link中所做的类似,但与我的功能相似。
再次感谢先进的