Generating random variables from a given distribution function using inversion sampling Given this distribution function $f(x)$ :
$$ 
f\left(x\right)=\left\{\begin{matrix}x+1,-1\le x\le0\\1-x,0<x\le1\\\end{matrix}\right.
$$
Generate random variables using Inverse sampling method in R:
here is my attempt :
f <- function(x){
ifelse(x<=0&&x>=-1,x+1,1-x)
}

integrate(Vectorize(f),-1,1)$value == TRUE
plot(Vectorize(f),xlim = c(-2,2))


$$ 
F\left(x\right)=\left\{\begin{matrix}\frac{x^2}{2}+x,-1\le x\le0\\x-\frac{x^2}{2},0<x\le1\\\end{matrix}\right.
$$
$F^{-1}$:
F_inver <- function(x){ifelse(x<=0&&x>=-1,1-sqrt(2*x+1),1-sqrt(-2*x+1))}


I believe that the my inverse function isn't correct

 A: The cumulative distribution function, $F(x)$, is given by
$$
F(x) = \int_{-\infty}^x f(t)dt
$$
So for, $- 1 \leq x \leq 0$,
\begin{align*}
F(x) &= \int_{-\infty}^x f(t)dt \\
 &= \frac{x^2}{2} +x + \frac{1}{2}
\end{align*}
and for $0 \leq x \leq 1$,
\begin{align*}
F(x) &= \int_{-\infty}^0 f(t)dt + \int_0^x f(t)dt \\
& = \frac{1}{2} + x - \frac{x^2}{2}
\end{align*}
Thus,
$$
F\left(x\right)=\left\{
\begin{align*}
&\frac{x^2}{2}+x + \frac{1}{2},-1 \leq x \leq 0 \\
&\frac{1}{2}  +x -\frac{x^2}{2},0< x \leq 1 
\end{align*}
\right.
$$
For $0 \leq y \leq \frac{1}{2}$,
\begin{align*}
y = F(x)  &\iff y = \frac{x^2}{2}+x + \frac{1}{2} \\
&\iff \frac{x^2}{2}  +x + \frac{1}{2}  - y = 0
\end{align*}
The last line is a second order polynomial equation whose determinant is $2y >0$.
The solutions are thus $-1 \pm \sqrt{2y}$. Since $-1 \leq 0 \leq x$, we have $x= -1 + \sqrt{2y}$
For $\frac{1}{2} \leq y \leq 1$,
\begin{align*}
y = F(x)  &\iff y = -\frac{x^2}{2}+ x + \frac{1}{2} \\
&\iff -\frac{x^2}{2}  +x + \frac{1}{2}  - y = 0
\end{align*}
Repeating the same process as before we find
$$
x = 1 - \sqrt{2(1-y)}
$$
Thus the inverse function of $F(x)$ (the quantile function) is given by:
$$
F^{-1}(y) = \left\{
\begin{align*}
&-1 + \sqrt{2y}, \ 0 \leq y \leq \frac{1}{2} \\
&1-\sqrt{2(1-y)}, \ \frac{1}{2} < y \leq 1 
\end{align*}
\right.
$$
