Search code examples
rvariablesrandommontecarloprobability-density

Generating random variable from density function


How can I generate a random variable of size n= 2914 if I have the density function?.

So the problem is that I have the density f(x) (function well defined)

P     <- function(a,e) { ( (1/6)(1^3) )-((a/2)(1^2)) +(((((a)^2)/2)+e)*1)}
D     <- function(u,mu,sigma) {dlogis(u,mu,sigma)}
K     <- function(u,a,e) {(((1/2)*(u^2))- (a*u) +(((a^2)/2)+e))}
H     <- function(u,mu,sigma){ plogis(u,mu,sigma, lower.tail = TRUE)}
Fprim <- function(u,a,e,mu,sigma) (1/P(a,e))(D(u,mu,sigma))(K(H(u,mu,sigma),a,e))

Fprim(1,a,e,mu,sigma)

df    <- function(u) Fprim(u,a,e,mu,sigma)

# Parameter n,a,e,mu,sigma
n<-2914; mu<- -0.42155226; sigma<- 0.60665552; a<- 0.43218138; e<- 0.02149706

I think I need to reverse and to use Monte Carlo, I don't know how to do?


Solution

  • There's always brute force...

    > cdf<-function(x) integrate(df,-20,x)$value
    > qdf<-function(x) optimize(function(z)(cdf(z)-x)^2,c(-20,20))$minimum
    > rdf<-function(n) sapply(runif(n),qdf)
    > x<-rdf(2000)
    > hist(x,freq=F)
    > xseq<-seq(-8,8,len=1000)
    > lines(xseq,sapply(xseq,df))
    

    enter image description here