Defining a probability density function in R (software), and sampling from it

4k Views Asked by At

I'm asked to generate a random sample from a logistic distribution with the PDF, $$f(x)=\frac{e^{-x}}{(1+e^{-x})^2}$$ without using the function

rlogis(...)

So I get that I need to define the function first:

f <- function(x){
    exp(-x)/(1+exp(-x))^2
    }

I don't exactly know how to define an RNG, however...

2

There are 2 best solutions below

2
On BEST ANSWER

The trick is to get it by a transformation from random numbers with a uniform distribution over $[0,1]$. Let $G$ be the (CDF) cumulative distribution function of the uniform distribution over $[0,1]$ and $F$ the CDF of the logistic with PDF $f(x)=e^{-x}/(1+e^{-x})^2$. Then for a value $p$ with $0<p<1$ we have, since $G(p)=p$ here, that $$ G(p)= F(u)$$ where $u$ is the point where $F(u)=p$.

Inverting $F$ gives: $$ u= F^{-1}(p)$$ If you transform the independent random numbers $p_1,\ldots, p_n$ with uniform distribution into $F^{-1}(p_1),\ldots,F^{-1}(p_n)$, these will have the logistic distribution (can be shown by calculating the CDF). So what remains for you to do is to find the inverse function of $F(u)$.

This method works -- in general -- for CDF's with a continuous PDF.

3
On

One possible approach:

f <- function(x) { exp(-x)/(1+exp(-x))^2 }

i<-1:100

W<- array ( runif ( i, min = -5, max = 5 ), 100 )

X<- apply ( W , 1 , FUN = f )