= Solution
{c}
The following <R (programming language)> 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 $V=1-U$ is again a <uniform distribution> draw, so the expression is the <quantile function> from (ii). The function `expm1(t)` evaluates $e^t-1$ accurately when $t$ is small, avoiding cancellation in $1-p^V$; `log1p(-p)` evaluates $\log(1-p)$. 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`. 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]{ref}
Back to article page