Suppose that we have a random variable with pdf like $f = \left\{ \begin{array}{ c l } x+1, x\in [-1,0] \\ -x+1, x\in (0,1] \end{array} \right.$ and we have to simulate it.
It's pdf is $F(x) = \left\{ \begin{array}{ c l } x^2/2+x+0.5, x\in [-1,0] \\ -x^2/2+x+0.5, x\in (0,1] \end{array} \right.$
two methods to simulate this can be found here http://web.ics.purdue.edu/~hwan/IE680/Lectures/Chap08Slides.pdf page 12.
My question is if we can simulate problems like that by fist simulate a random U(0,1) and
if it is smaller than the probability $P(x\in [-1,0])=1/2$ simulate from the first part with inverse transformation $\sqrt{2U}-1$ but for a $U\sim Unif(0,1/2=P(x\in [-1,0]))$
and if it is bigger simulate with inverse transformation $1-\sqrt{(2(1-U))}$ using a $U\sim Unif(1/2,1)$.
When I make the histogram it seems to working, but is it correct?
[code]rand=function(){
if(runif(1,0,1)<=1/2){x=sqrt(2*runif(1,0,1/2))-1}else{
x=1-sqrt(2-2*runif(1,1/2,1))
}
return(x)
}
pri=NULL
for(i in 1:10000)
{
pri=c(pri,rand())
}
hist(pri,prob=T)[/code]


