Lab Wk8soln PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

UNIVERSITY OF NEW SOUTH WALES

SCHOOL OF MATHEMATICS AND STATISTICS


MATH3821 Statistical Modelling and Computing
Term Two 2020

Week 8 Lab Solutions


1. (a)
Z 1
exp(exp(x))dx = E(exp(exp(U ))
0

where U is uniformly distributed on [0, 1].


Approximation in R:
u <- runif(10000)
mean(exp(exp(u)))

## [1] 6.291558
(b) Because the function exp(−x2 ) is symmetric about the origin,

Z ∞ Z ∞
exp(−x2 )dx = 2 exp(−x2 )dx.
−∞ 0

Now,

Z ∞ Z 1  2 !
2 1 1
exp(−x )dx = exp − −1 du
0 0 u2 u

(we have made the transformation u = 1/(1 + x)).


Now approximate the integral:
u <- runif(10000)
2 * mean(1 / u ^ 2 * exp(-(1 / u - 1) ^ 2))

## [1] 1.763603

(The true answer is π ≈ 1.77).
(c)
Z 1 Z 1
exp((x + y)2 )dydx = E exp((U1 + U2 )2 )

0 0

where U1 , U2 are independent uniformly distributed random variables on [0, 1].


Now approximate the integral:
u1 <- runif(10000)
u2 <- runif(10000)
mean(exp((u1 + u2) ^ 2))

## [1] 4.925057
(d) With Iy (x) defined by 
1 if y < x
Iy (x) =
0 otherwise

1
we can write

Z ∞ Z x Z ∞ Z ∞
exp(−(x + y))dydx = exp(−(x + y))Iy (x)dydx.
0 0 0 0

Now make the transformations u1 = 1/(1 + x), u2 = 1/(1 + y). We have

Z ∞ Z ∞
exp(−(x + y))Iy (x)dydx =
0 0
Z 1 Z 1     
1 1 1 1
exp − + − 2 I 1
u2 −1
− 1 .
0 0 u21 u22 u1 u2 u1
 
1
Note that I u1 −1 u1 − 1 = Iu1 (u2 ) (since
2

1 1
−1< −1
u2 u1
if and only if u1 < u2 ).
Now approximate the integral:
u1 <- runif(10000)
u2 <- runif(10000)
z1 <- 1 / u1 - 1
z2 <- 1 / u2 - 1
mean(1 / u1 ^ 2 / u2 ^ 2 * exp(-(z1 + z2)) * (u1 < u2))

## [1] 0.5010676
(The true answer is 0.5).

2. invsim <- function(p) {


if(sum((p < 0)) != 0)
stop("Some supplied probability function values are negative")
#
# If the probability function values don't sum to 1
# then rescale.
#
p <- p / sum(p)
cumsum <- p[1]
y <- 1
u <- runif(1)
while(u >= cumsum) {
cumsum <- cumsum + p[y + 1]
y <- y + 1
}
y
}

3. reject <- function() {


p <- rep(c(0.11, 0.09), times = 5)
y <- sample(1:10, 1) + 4
while(runif(1) > p[y - 4]/0.11) {
y <- sample(1:10, 1) + 4
}

2
y
}

4. Suppose that
F (x) = xn 0 ≤ x ≤ 1
where n is a positive integer. A random variable with density function

nxn−1 0 ≤ x ≤ 1

f (x) =
0 otherwise

has this distribution function.


Let g(x) be the uniform density on [0, 1],

1 0≤x≤1
g(x) =
0 otherwise.

Now,
f (x)
max = max f (x) ≤ n.
0≤x≤1 g(x) 0≤x≤1

We implement the rejection algorithm in R as follows:


function(n) {
y <- runif(1)
while(runif(1) >= y^(n - 1)) {
y <- runif(1)
}
y
}

You might also like