-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathacceptreject.m
74 lines (65 loc) · 1.66 KB
/
acceptreject.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
%this m-file uses the acceptance/rejection
%method to sample from the triangular and
%truncnated normal densities.
clear;
clc;
rand('seed',sum(100*clock));
nkeep = 25000;
%--------------------------------
%triangular density
%--------------------------------
M=1;
a=-1;
b=1;
triang_keep = zeros(nkeep,1);
counter =0;
while counter < nkeep
U = rand(2,1);
U1 = U(1); U2 = U(2);
if M*U2 < 1 - abs( a + (b-a)*U1)
counter = counter+1;
x = a + (b-a)*U1;
triang_keep(counter,1) = x;
end;
end;
%--------------------------------
%Truncated Normal TN_[0,4] (1,1) density
%--------------------------------
a = 0;
b = 4;
normcons = normcdf( (4-1)/1 ) - normcdf( (0-1)/1 ) ;
M = normpdf(1,1,1)/ normcons;
tn_keep = zeros(nkeep,1);
counter = 0;
while counter < nkeep
U = rand(2,1);
U1 = U(1); U2 = U(2);
if M*U2 < (normpdf(a + (b-a)*U1,1,1)/normcons)
counter = counter+1;
x = a + (b-a)*U1;
tn_keep(counter,1) = x;
end;
end;
%plotting the actual Triangular and TN_{0,4](1,1) density
xgrid = linspace(-1,1,75);
density = 1 - abs(xgrid);
mu = 1;
sig = 1;
xgrid2 = linspace(0,4,75);
densitya = normpdf(xgrid2,mu,sig);
density2 = densitya/normcons;
%plot the results
[dom ran] = epanech2(triang_keep);
[dom2 ran2] = epanech2(tn_keep);
subplot(121),
plot(dom,ran,'k');
xlabel('X');
ylabel('Triangular Density');
hold on;
plot(xgrid,density,'r.');
subplot(122),
plot(dom2,ran2,'k');
xlabel('X');
ylabel('Truncated Normal Density');
hold on;
plot(xgrid2,density2,'r.');