Question

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?

Was it helpful?

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

OTHER TIPS

There are multiple options for generating data from a given distribution.

The simplest if you have the inverse cumulative distribution (I can't tell which of the above are supposed to be which) is to generate $n$ observations from a uniform distribution and plug those values into the inverse of the CDF.

A couple of others include Rejection Sampling and Metropols-Hastings sampling. Links from those pages can help you find others if that is not enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top