I need to generate a random variable with density function: $$ f(x)= \begin{cases} a (1+|x-2|) , & {-1 \le x \le 4} \\ 0, & \text{elsewhere} \end{cases} $$
For that I need to inverse the probability function and use a uniform variable to generate the variable with this distribution.
I need to use the inverse transfom method. First, I want to calculate the integral, so I divided the function into two parts and got this:
$$ \int_{-1}^4f(x)dx = \int_{-1}^2a(3-x) + \int_{2}^4a(x-1) = 3ax-{x^2 \over 2} + {ax^2 \over2} - ax $$
Then I need to inverse this, but I got stuck, I tried to use the quadratic formula but I'm not sure this is the right direction.
Please help me solve this.
Thanks.
For the inverse transform method, we need an expression for the cumulative distribution function $$ F(x)=P(X<x)=\int_{-\infty}^xf(t)\,\mathrm dt.$$ If $x\le -1$, clearly $F(x)=0$. If $-1\le x\le 2$, $$\begin{align}F(x)&=\int_{-1}^xa(3-t)\,\mathrm dt\\& =\left[3at-\frac12at^2\right]_{-1}^x\\&=3ax-\frac a2x^2+\frac 72a.\end{align}$$ If $2\le x\le 4$, $$\begin{align}F(x)&=\int_{-1}^2f(t)\,\mathrm dt+ \int_{2}^xf(t)\,\mathrm dt\\&=\frac{15}2a+\int_2^xa(t-1)\,\mathrm dt\\&=\frac{15}2a+\left[\frac12at^2-at\right]_2^x\\&=\frac{15}2a+\frac12ax^2-ax.\end{align}$$ Ultimately, we need $F(x)=1$ for $x\ge 4$. Plugging $x=4$ into the result for $2\le x\le 4$, we obtain $$1=\frac{15}2a+8a-4a, $$ so that we conclude $a=\frac{2}{23}$. In summary, this gives us $$F(x)=\begin{cases}0,&x\le -1\\ \frac{7+6x-x^2}{23},&-1\le x\le 2\\ \frac{15-2x+x^2}{23},&2\le x\le 4\\ 1,&4\le x \end{cases} $$ For the inverse function $F^{-1}\colon[0,1]\to[-1,4]$ we can neglect the $x<-1$ and $x>4$ cases. The point $F(2)=\frac{15}{23}$ is of special interest:
In summary, $$ F^{-1}(y)=\begin{cases}3-\sqrt{16-23y},&0\le y\le\frac{15}{23}\\ 1+\sqrt{23y-1},&\frac{15}{23}\le y\le 1\end{cases}$$ So to generate a random variable following the density function $f$, you generate a uniformly distributet randomm variable in $[0,1]$ and apply this $F^{-1}$ to it.