Random Variable Generation
Random Variable Generation
scatterplot
1.0e+09
x2t+1
0.6
0.4
0.0e+00
0.2
0.0
Density
0.8
1.0
2.0e+09
Histogram of U
0.0e+00
1.0e+09
x2t
2.0e+09
2. Inversion Method
The idea is to set
f (x) = F (x) = U
Rx
0
ex dx = 1 ex
1
ba
Hist of Exp( 1 )
0.0
5
10
15
20
10
Hist of Exp( 2 )
1.0
3
x
12
0.0
0
Density
Density
0.4
Density
0.3
0.0
Density
0.8
3. Acceptance-Rejection Method
Using Mg(x) to envelop f(x) which is the targeted distribution
P(accept x) =
f (x)
M g(x)
1
M
f (x)
g(x)
f (x)
g(x)
2
=
ex
Maximum of
Thus M =
x2
2
f (x)
g(x)
2 12
e
2
exp( 12 ((x
f (x)
.
M g(x)
2 x
e 2
1)2 1))
is acheived at x = 1.
and
f (x)
M g(x)
= exp( (x1)
)
2
num = 0
iter = 10000
result =rep(0,iter)
for (i in 1:iter){
rejected = 0
repeat{
X = -log(runif(1)) #Using uniform to generate exponential distribution g(x)
U = runif(1,min=0,max=1)
if( U< exp(-(X-1)^2/2)){ #accept x
break}
rejected = rejected + 1}
num = num + rejected # number of rejected
#accept X as a realization of truncated normal
#Now need to flip a coin to generate the whole normal distribution
if (runif(1)<= 0.5) {Z = X
}else {Z =-X}
result[i] = Z
}
rejection_rate = num/(iter+num)
acceptance_rate = 1-rejection_rate
hist(result, breaks = 30, prob=T, xlab = "Z",
main = paste("Histogram of Z, Acceptance rate= ", round(acceptance_rate,2)))
curve(dnorm(x,mean=0,sd=1), lwd=2, add=T, col="blue")
0.2
0.0
0.1
Density
0.3
0.4
Polar Transformation
Using polar transformation to generate N(0, 1) random variable$
~Unif[0, 2], So = 2u1
normsamp = function(n) {
u1 = runif(n)
u2 = runif(n)
theta = 2*pi*u1
t = -log(u2)
r = sqrt(2*t)
x = r*cos(theta)
y = r*sin(theta)
res = list("X"=x, "Y"=y)
return(res)
}
sample = normsamp(1e4)
par(mfrow =c(1,2))
hist(sample$X , breaks =30, prob =T, xlim =c(-4,4) ,
xlab ="X", main = "Histogram of X")
curve(dnorm(x,mean =0, sd =1) ,lwd =2, add =T, col="blue")
hist(sample$Y , breaks =30, prob =T, xlim =c(-4,4) ,
4
Histogram of Y
0.3
0.0
0.1
0.2
Density
0.2
0.1
0.0
Density
0.3
0.4
0.4
Histogram of X
0
Y