2
$\begingroup$

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?

$\endgroup$
0

1 Answer 1

2
$\begingroup$

I suppose you mean

df <- function(u)  Fprim(u,a = 0.43218138, e = 0.02149706, mu = -0.42155226, sigma = 0.60665552)

I propose

 x <- seq(-20,20,length=10001)
 y <- df(x)
 y1 <- cumsum(y)*diff(x)[1]

 pf <- approxfun(x,y1)
 qf <- approxfun(y1,x)
 rf <- function(n) qf(runif(n))

The functions qf, pf and rf are the quantile, cdf, and random generator for the density df. So you just end by

rf(2914)
$\endgroup$
2
  • $\begingroup$ thank's a lot for your answer, I want to understand what you did, so the cumulative distribution is the y1, or what is this line y1 <- cumsum(y)*diff(x)[1]. So if my question is stupid but I just start to study r 1 week ago, $\endgroup$
    – Lea
    Commented Oct 19, 2013 at 0:26
  • $\begingroup$ Yes, y1 is the cdf! $\endgroup$
    – Elvis
    Commented Oct 19, 2013 at 3:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.