I have a specific density function and I want to generate random variables knowing the expression of the density function.
For example, the density function is :
df=function(x) { - ((-a1/a2)*exp((x-a3)/a2))/(1+exp((x-a3)/a2))^2 }
From this expression I want to generate 1000 random elements with the same distribution.
I know I should use the inverse sampling method. For this, I use the CDF function of my PDF which is calculated as follows:
cdf=function(x) { 1 - a1/(1+exp((x-a3)/a2))
The idea is to generate uniformly distributed samples and then map them with my CDF functions to get an inverse mapping. Something like this:
random.generator<-function(n) sapply(runif(n),cdf)
and then call it with the desired number of random variables to generate.
random.generator(1000)
Is this approach correct?
The first step is to take the inverse of your cdf function, which in this case can be done with simple arithmetic:
Now you want to call the inverse cdf with standard uniformly distributed random variables to sample:
This is a histogram of 10000 simulated values:
And here is the plot of the pdf: