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]
Yes, your code generates the correct results, but as you can see from the calculations below, it's hard to understand. I suggest sticking with the linked lecture notes and use
runif(1,0,1), which represents $\mathrm{Unif}(0,1)$.The composition algorithm in the linked notes:
The composition algorithm in the question body contains a rescaled version of $U_2$.
These figures illustrates the how the code works.
If we increase the sample size from 10k to 50k, the histogram looks more similar to the triangular distribution on $[-1,1]$.
We increasing the class number from 20 to 50 in order to take a closer look of the data.
My code