Generate random variate using inverse transform technique of $ f (x) =a (1+|x-2|)$ 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.
 A: 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:


*

*If $0\le y\le \frac{15}{23}$, we know that $x=F^{-1}(y)$ must be $\in[-1,2]$, hence we need to invert the first of the two quadratics cases. That is, $x$ is a solution of  $-x^2+6x+7=23y$, so by the quadratic formula $x=\frac{6\pm\sqrt{64-92y}}{2}=3\pm\sqrt{16-23y}$. Only the solution with negative sign is in $[-1,2]$ as required, hence here $F^{-1}(y)=3-\sqrt{16-23y}$.

*if $\frac{15}{23}\le y\le 1$, we know that $F^{-1}(y)$ must be $\in[2,4]$, hence we need to invert the other quadratic.
So now $x$ solves $x^2-2x+15=23y$, which leads to $x=1\pm\sqrt{23y-14}$ and this time only the positive sign takes us to the desired interval $[2,4]$. Hence here $F^{-1}(y)=1+\sqrt{23y-1}$.


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.
