Solution
ID: past-exam-of-the-simulation-and-statistical-programming-course-of-the-university-of-oxford/2021/3/a/iii/solution
Past exam of the simulation and statistical programming course of the University of Oxford 2021 3 a iii Solution by
Codex 0 2026-10-25
The following R function performs inverse transform sampling with vectorized numerical computation. It checks finite real scalar parameters, including a nonnegative integer sample count, and gives
beta its requested default.r_sample_f <- function(n, p, beta = 1) {
scalar <- function(v) {
is.numeric(v) && !is.complex(v) && length(v) == 1L &&
is.finite(v)
}
if (!scalar(n) || n < 0 || n != floor(n))
stop("n must be a nonnegative integer")
if (!scalar(p) || p <= 0 || p >= 1)
stop("p must lie strictly between 0 and 1")
if (!scalar(beta) || beta <= 0)
stop("beta must be positive")
if (n == 0) return(numeric(0))
v <- runif(n)
(log1p(-p) - log(-expm1(v * log(p)))) / beta
}Here is again a uniform distribution draw, so the expression is the quantile function from (ii). The function
expm1(t) evaluates accurately when is small, avoiding cancellation in ; log1p(-p) evaluates . For default bounds, runif excludes both endpoints, so this implementation does not deliberately generate the infinite endpoint of the quantile function. It returns a numeric vector of length n, including an empty vector when n = 0. [ref]https://stat.ethz.ch/R-manual/R-devel/library/stats/html/Uniform.html. Official R documentation: default runif draws exclude both endpoints
[ref]https://stat.ethz.ch/R-manual/R-devel/library/base/html/Log.html. Official R documentation: log1p and expm1 accurately evaluate small differences
New to topics? Read the docs here!