%this program generates variates from the triangular 
%distribution, using the method of composition and the 
%method of inversion. 

clear;
clc;
rand('seed',sum(100*clock));
sims = 50000;
temp = rand(sims,1);
Z = .5*sign(temp-.5) + .5;
    %this creates a 1000 times 1 vector of draws from the marginal
    %distribution of z. We associate z=1 with the conditional distribution
    %given x>0 and conversely when z=0
    
u = rand(sims,1);   %U(0,1) draws
cond_positive = 1 - sqrt(1-u);
cond_negative = -1 + sqrt(u);
draws_keep = Z.*cond_positive + (1-Z).*cond_negative;
hist(draws_keep,30);