Source: Oxford's released examination PDF, pages 211–214, dated 22 June 2023. The cover is on page 211; questions 1, 2 and 3 are on pages 212, 213 and 214 respectively. All 22 smallest subparts are answered below. The original PDF confirms the missing qualification in 2(a)(iv) and the return-value ambiguity in 3(c)(ii), discussed where they arise.
Generate independent and identically distributed random variables with probability density function , evaluate for each draw, and return the Monte Carlo estimatorLinearity of expectation makes this an unbiased estimator: . Independence and the specified variance give . Its Monte Carlo standard error is therefore , and the strong law of large numbers gives convergence to almost surely.
Apply Chebyshev's inequality to the Monte Carlo estimator:Thus suffices, givingThis is a finite-sample probability guarantee for every target satisfying the given variance assumption. It is a sufficient sample count supplied by the inequality, rather than a claim that every such target actually needs a million draws.
The central limit theorem gives , so, with the cumulative distribution function of the standard normal distribution,The error has two tails. Using the supplied quantile, whose two-sided coverage is approximately , givesThe supplied quantile would be appropriate for a one-sided calculation; it would give only approximately two-sided coverage. Using the exact quantile instead of would give draws; we consistently use the paper's rounded value below.
For routine Monte Carlo integration, the central limit theorem calculation is preferable as a practical budget: it uses about one fifteenth as many draws as the Chebyshev's inequality bound. However, its coverage is approximate. Finite variance alone supplies no universal rate of convergence to the normal distribution; an integrand with large skewness or a heavy-tailed distribution can make the approximation poor even at a large sample count. If an unconditional finite-sample guarantee is required under only the stated assumptions, use the Chebyshev's inequality budget.
Integrating the envelope shows . One trial of rejection sampling draws and an independent from the uniform distribution on , and accepts if . Repeat with fresh independent random variables after each rejection. Ratios need only be evaluated where ; the envelope makes the target zero wherever .
For any measurable set , integration of the conditional probability of acceptance givesTaking the whole domain gives acceptance probability , and dividing gives . Fresh trials therefore supply independent and identically distributed random variables with target probability density function . The corresponding Monte Carlo estimator isThe proposal count up to and including one acceptance has the geometric distributionFor example, the tail-sum formula gives . Thus the expected cost is proposal draws per accepted target draw.
Stop rejection sampling when exactly target draws have been accepted. The total proposal count is a sum of independent waiting times with geometric distribution, equivalently a negative binomial distribution counting trials. ConsequentlyThe accepted-sample Monte Carlo estimator then has the approximate precision from (a)(iii). The displayed proposal cost is an expected value, which need not be an integer. Spending this many proposals in advance does not ensure that target draws will have been accepted.
With a fixed budget of independent proposal trials, the accepted count has binomial distribution with success probability . HenceFor , the central limit theorem gives the one-sided approximationUse , since now only the lower tail of the accepted count matters. Requiring and solving the resulting quadratic equation in gives the one-sided normal approximation for a rejection proposal budgetEquivalently, before rounding, this is . For the value in (a)(iii),When , every proposal is accepted and exactly. Otherwise the positive safety margin above allows for random fluctuations in the number accepted. The average cost in (b)(ii) describes stopping at the th acceptance; this answer chooses a deterministic budget that reaches that acceptance with approximately probability.
The approximation requires a sufficiently accurate normal distribution approximation to the binomial distribution. An exact budget can instead be found from its tail probabilities. Also, a chance of enough accepted draws and approximate precision conditional on obtaining them are separate claims: their intersection is not automatically a event.
Draw independent and identically distributed random variables and use the importance weight . The importance sampling estimator isThe envelope supplies the support condition for importance sampling. Since , this is an unbiased estimator. Moreover, , soHere . Subtracting the squared expected value and dividing by proves the bounded-weight importance-sampling moment bound in the requested form:
The definition of and (c)(i) give . Nonnegativity of the variance strengthens the lower bound toIn fact the variance of one weighted observation is exactlyIt is finite by the envelope. For , the central limit theorem gives approximate two-sided coverage , so the paper's rounded quantile yieldsIf , the weighted observation equals almost surely, and one draw is sufficient. These are theoretical budgets: and may themselves be unknown and need preliminary estimation in an implementation.
Compare with the average rejection sampling cost . Ignoring integer rounding, importance sampling uses fewer proposal draws at the same approximate precision precisely whenFor literal integer budgets, the comparison is . The simpler strict inequality is the intended leading-order condition. The bound alone does not ensure an improvement when ; this is a proposal-budget variance comparison of importance and rejection sampling.
Write where , assigning zero elsewhere. The envelope ensures , and is nonnegative. Integrating its joint probability density over the auxiliary coordinate givesConsequently . This proves normalization of a probability distribution; the change of integration order is justified by Tonelli's theorem.
The coordinates are generally dependent. For , their conditional probability density isThus has a uniform distribution on an interval whose endpoint depends on . They are independent exactly when is constant for -almost every , since only then do these conditional laws agree. In particular, is an exception: and are independent. An unconditional answer that they can never be independent would therefore be too strong.
Integrating the joint probability density over the auxiliary coordinate, as in (i), gives the marginal distributionIn particular, augmenting with preserves the target probability distribution of . The other marginal distribution, though not needed to identify , is for . It need not be a uniform distribution on .
For the proposed joint probability density , define the acceptance indicator functionOn the proposal's support the importance weight is . Therefore the requested augmented-space importance sampling estimator isIts expected value is , provided . This is not the ordinary estimator from question 1. Taking the conditional expectation of this augmented estimator given all produces that ordinary estimator, because . This is the Rao-Blackwell identity for a fixed-denominator rejection estimator.
Use the same acceptance indicator functions and set , . The rejection sampling estimator based on these proposals is the mean over the accepted observations:For , any fixed convention, such as zero, is harmless asymptotically. The are independent and identically distributed random variables with Bernoulli distribution and success probability , so the strong law of large numbers gives almost surely. In particular eventually almost surely. The exact identitythen holds whenever . Wherever , it follows thatA qualification is missing from the printed claim: the quotient must be defined eventually. A convenient sufficient assumption is and . Indeed, another application of the strong law of large numbers gives , ensuring that is eventually nonzero. This proves the stated quotient limit under that assumption.
As printed, the assertion is false as a universally defined quotient. For example, makes both estimates zero for every . Even excluding that example is insufficient: take to be the uniform distribution on , , and for and otherwise. Then is a simple symmetric random walk, which returns to zero infinitely often almost surely, leaving the quotient undefined infinitely often.
With integrability but no assumption , the exact multiplicative identity remains valid, and both estimates converge to almost surely. In particular almost surely. One may alternatively define the quotient's removable cases as ; that explicitly extended quantity always converges to one. These are valid repairs of the source's unrestricted statement.
Fix a proposal with , and abbreviate , and . The envelope says . Assuming fresh independent uniform distribution draws at both stages, the law of total probability givesThe second term includes both reaching the residual test and passing it. If , the envelope forces and the first test accepts with probability one; the second-stage ratio is never evaluated. This is squeeze rejection sampling.
Average the conditional probability in (i) over :This is exactly the acceptance mass for an unnormalized rejection envelope. In normalized form the envelope is , giving the same acceptance probability. Here bounds the ratio of the unnormalized functions, so its value need not equal the envelope constant for the normalized probability density functions.
The squeeze changes the number of expensive target evaluations, while preserving the per-proposal acceptance probability. The expected number of proposals per accepted draw is .
For a measurable set , (i) gives the joint acceptance probabilityDivide by from (ii). The resulting conditional probability isThus every accepted value has target probability density function . Repeating rejected trials with fresh independent random variables does not change this law: the contribution from acceptance on trial is multiplied by , and summing that geometric series gives the same conditional law. Independent repetitions produce independent target draws.
The proposal's normalization of a probability distribution isThis is the Laplace distribution with location zero and scale one. For example, generate its magnitude from the exponential distribution with rate one and give it an independent fair sign. The target is the standard normal distribution, with .
To obtain the tight envelope, let . By completing the square,Equality occurs at , so is the smallest valid envelope constant. It maximizes the acceptance probability for this fixed proposal. The supplied lower bound must be clipped at zero to satisfy the algorithm's nonnegativity requirement:This is valid because for , while is everywhere positive. Its support is .
Here is the fully specified squeeze rejection sampling procedure. Draw with probability density function , independently draw , and compute and . If , return immediately. Otherwise evaluate , independently draw , and return if . On rejection restart with fresh draws. In this example everywhere, so the residual denominator is positive.
Avoiding a target evaluation means accepting at the first test. Its unconditional probability for one proposal isFor comparison, the overall acceptance probability is . The first-stage saving is the fraction of proposals requiring no target evaluation, including both eventual accepted and rejected proposals in the denominator; it is not conditional on acceptance.
The following R code implements the given recursion for the Cholesky decomposition. The input is assumed to be a real symmetric matrix that is a positive-definite matrix.
mychol <- function(A) {
n <- nrow(A)
if (n == 1L) return(matrix(sqrt(A[1L, 1L]), 1L, 1L))
j <- 2L:n
L <- matrix(0, n, n)
L[1L, 1L] <- sqrt(A[1L, 1L])
b <- A[j, 1L, drop = FALSE] / L[1L, 1L]
L[j, 1L] <- b
S <- A[j, j, drop = FALSE] - tcrossprod(b)
L[j, j] <- mychol(S)
L
}Here
tcrossprod(b) is the outer product . The drop = FALSE arguments preserve matrix dimensions, including the final one-by-one subproblem, and the base case also returns a matrix.To verify correctness, partition . The code sets , and recursively factors . This Schur complement is a positive-definite matrix: for ,If is the recursive answer, then the returned lower triangular matrix satisfiesThe one-dimensional identity starts this mathematical induction proof. Each recursive call reduces the matrix size by one and therefore terminates.
An inverse matrix exists only if the lower triangular matrix has no zero diagonal entries; this necessary assumption is implicit in the request for . PartitionWriting its inverse in the same block form and multiplying gives the recursive inverse of a lower triangular matrix:Indeed the lower-left block of the product is , and the diagonal blocks are identities. This gives an implementation with no call to
solve:ltinv <- function(L) {
n <- nrow(L)
if (n == 1L) return(matrix(1 / L[1L, 1L], 1L, 1L))
j <- 2L:n
Cinv <- ltinv(L[j, j, drop = FALSE])
B <- matrix(0, n, n)
B[1L, 1L] <- 1 / L[1L, 1L]
B[j, j] <- Cinv
B[j, 1L] <- -as.vector(Cinv %*% L[j, 1L, drop = FALSE]) / L[1L, 1L]
B
}The preserved matrix dimensions also handle . A mathematical induction using the block identity proves that every returned matrix is the desired inverse. Applied to the Cholesky decomposition from (a), all diagonal entries are positive, so all divisions are valid.
Each state has exactly neighbours: choose one occupied coordinate and one unoccupied coordinate to swap. The normalized proposal distribution is thereforeThe swap relation is symmetric and the number of neighbours is constant, so . The discrete uniform distribution used as the prior distribution is also constant on , with mass . Both factors cancel in the Metropolis–Hastings acceptance probability.
Let and . The displayed multivariate normal distribution presupposes that the covariance matrix is a positive-definite matrix, so is a symmetric matrix. Expanding the difference of quadratic forms givesConsequentlyThe truncation at zero is essential: a log acceptance ratio can be positive, but the logarithm of an acceptance probability cannot.
For the particular proposed swap, let be the coordinate changing from zero to one and the coordinate changing from one to zero. Then , and the untruncated scalar simplifies further toOnly two rows and four entries of are needed for this evaluation. This is Metropolis sampling on fixed-cardinality subsets.
The source's function name suggests a log return value, and (c)(i) asks for , while the wording here and in (c)(iv) asks for the acceptance probability. We use the literal probability-returning convention and explicitly exponentiate the result of (c)(i):
mylogapp <- function(x, u, v, sigma_inv) {
d <- v - u
log_ratio <- as.numeric(crossprod(d, sigma_inv %*% (x - (u + v) / 2)))
log_alpha <- min(0, log_ratio)
exp(log_alpha)
}Thus
mylogapp returns , and (c)(iv) compares it directly with a uniform distribution draw. Taking the minimum before exponentiating prevents overflow. The arguments are assumed to be valid neighbouring states. A log-returning convention would instead return log_alpha and compare log(runif(1)) with it; the two conventions implement the same Metropolis–Hastings algorithm, provided the caller uses the matching comparison.The Cholesky decomposition gives . If , reversal of factors in a matrix inverse givesHence the required R implementation is
invsigma <- function(sigma) {
L <- mychol(sigma)
B <- ltinv(L)
crossprod(B)
}Here
crossprod(B) computes . Using tcrossprod(B) would compute , which generally differs from . Both helper functions preserve the one-by-one matrix case.Choose distinct coordinates uniformly for the starting ones; each element of then has starting probability . At each iteration choose one current one and one current zero uniformly and swap them. This implements the normalized proposal distribution from (c)(i), remains in , and needs just one precomputed matrix inverse.
mymcmc <- function(x, k, sigma) {
n <- length(x)
stopifnot(length(k) == 1L, is.finite(k), k == floor(k),
k > 0L, k < n, is.matrix(sigma),
all(dim(sigma) == c(n, n)))
sigma_inv <- invsigma(sigma)
u <- integer(n)
u[sample.int(n, k, replace = FALSE)] <- 1L
draws <- matrix(0, 100L, n)
for (iteration in seq_len(100L)) {
ones <- which(u == 1L)
zeros <- which(u == 0L)
i <- ones[sample.int(length(ones), 1L)]
j <- zeros[sample.int(length(zeros), 1L)]
v <- u
v[i] <- 0L
v[j] <- 1L
alpha <- mylogapp(x, u, v, sigma_inv)
if (runif(1L) < alpha) u <- v
draws[iteration, ] <- u
}
colMeans(draws)
}Sampling positions with
sample.int and then indexing into ones or zeros also works when or . In R, a call such as sample(ones, 1) would incorrectly sample from 1:ones when ones is a single numeric value greater than one.The code records the state after each of exactly transitions, including repetitions after rejection. Its answer is the vector Monte Carlo estimatorThis estimates the posterior mean coordinate by coordinate; because each coordinate is binary, its entries estimate the posterior probabilities of inclusion. Every stored state has coordinate sum , so the estimated means lie in and sum to .
For neighbouring states, the symmetry of the proposal and the Metropolis–Hastings acceptance probability give detailed balance:Thus the posterior distribution is a stationary distribution. Any two states in can be connected by moving the ones that occupy the wrong positions, and the multivariate normal distribution gives strictly positive target masses. The resulting Markov chain is therefore an irreducible Markov chain, and its long-run state averages estimate the posterior mean.
The requested iterations are a finite approximation, without a convergence guarantee or discarded burn-in. A randomly chosen starting subset has the prior distribution, rather than generally the posterior distribution. No aperiodicity assumption is needed for the finite-state Markov chain ergodic theorem for averages; indeed a uniform two-state target with gives a period-two alternating chain. This does not invalidate either the code or the state-average estimator.
Source: Oxford's released examination PDF, pages 203–206, dated 24 June 2021. The cover is on page 203; questions 1, 2 and 3 are on pages 204, 205 and 206 respectively. All three questions and all 19 smallest answer parts are solved below, including the third question although only the best two counted towards the examination mark. The original PDF confirms the inconsistent return-field name in 3(c)(ii), addressed there.
Write . The two multivariate normal distribution probability density functions have ratioHere is the Euclidean norm. Consequently the smallest rejection sampling envelope constant, and its acceptance probability, areThe supremum is attained at ; hence no smaller constant can dominate the ratio. Draw and an independent from the uniform distribution on . Accept whenotherwise repeat with fresh independent random variables. One can generate using a random vector with independent standard normal distribution coordinates.
For any measurable set , the joint acceptance probability is . Dividing by proves that the returned random vector has probability density function . The number of proposals has a geometric distribution on the positive integers, with expected value . When , every proposal is accepted.
The moment-generating function of a standard normal distribution gives . Using independence of the coordinates,The accepted draws are independent and identically distributed random variables, so their sample mean is an unbiased estimator and has varianceThis counts accepted draws, requiring proposals in expectation.
An importance weight has expected value . From the ratio in (a),The supplied normal distribution transform applies with quadratic coefficient , giving each factor . ThusFor , the base exceeds one because : importance weight variance increases exponentially with dimension. For , the importance weight is identically one and its variance is zero. This calculation concerns the importance weight, rather than the weighted integrand.
For the new integrand, and , independently of dimension. Chebyshev's inequality therefore yieldsA sufficient positive integer sample count isThe ceiling function ensures that the bound is at most , so the strict-error event in the question has probability at least . The required number of accepted draws is independent of ; their expected proposal count is .
At equal sample count, rejection sampling eventually has smaller variance for fixed ; at equal expected proposal cost, importance sampling eventually wins. The distinction matters because a sample of the rejection sampling estimator means an accepted draw.
For the importance sampling estimator, all coordinates contribute to the importance weight although only one enters the integrand. The same normal distribution transform as in (c), now with linear coefficient for coordinate one, givesBoth estimators are unbiased estimators of , andFor fixed , the first variance grows exponentially while the second stays constant. This is the benefit of returning exact target draws in rejection sampling. However, obtaining those draws costs proposals each on average.
To compare computational work, multiply each variance by its expected proposal count. For importance sampling that count is ; for rejection sampling it is . The ratio of the resulting cost-normalized variances isbecause . Thus importance sampling eventually gives better precision for the same expected number of proposals, assuming comparable work per proposal. This is an asymptotic cost comparison, not a guarantee that a fixed small computing budget produces any accepted draws. Both methods still deteriorate exponentially in this comparison. For they coincide and every proposal is accepted.
Sample-count and expected-proposal-cost comparisons for the one-coordinate integrand at sigma squared equal to two
. Details. A practical improvement is to exploit the integrand's one-coordinate structure directly: average for standard normal distribution draws , without generating unused coordinates. The optimal change of proposal distribution in (iii) improves further.
The integrand is positive, so the minimum-variance importance distribution is its target-weighted probability density function, normalized by :By completing the square,Thus is the multivariate normal distribution , where is the first standard basis vector. Its importance weight and weighted integrand areA variance cannot be negative, and this proposal makes every summand constant, proving optimality directly. It is admissible under the arbitrary-proposal condition even though its mean vector is not zero. Although optimal proposals usually involve an unknown normalizing integral, here both that integral and the resulting normal distribution are explicit.
For the exponential distribution with rate , the cumulative distribution function is for , and zero for . Its quantile function isFor inverse transform sampling, draw from the uniform distribution on and return . Equivalently return , since has the same uniform distribution. Indeed, for , .
Integrating the conditional distribution against the exponential distribution probability density function gives, for integer ,Here the gamma function identity evaluates the integral. Henceon . Put and . The geometric series gives . Its generalized inverse, the quantile function, isThis is the smallest nonnegative integer for which ; dividing by reverses the inequality. Draw from the uniform distribution on and use this formula. The commonly used expression has the same probability distribution, but differs from the exact generalized inverse when is precisely a jump value of the cumulative distribution function. Such values have probability zero for an ideal continuous uniform draw.
Write . The target Poisson distribution and proposal geometric distribution have probability mass functions and . Their ratio isThe successive ratio shows that a maximizing integer is , with a tie at when is an integer. Thus the tight envelope isFor any fixed , draw using (ii)'s inversion formula with this new parameter, and draw an independent from the uniform distribution on . Accept whenotherwise restart. The acceptance probability is and the expected number of proposals is .
To minimize that expected count, set . The exact answer isHere is a proof that includes the changes of maximizing integer. Each is a convex function of , since its second derivative is . Their pointwise maximum is also a convex function. When is fixed its derivative isIf , take , where changes from on the left to on the right. The left derivative is nonpositive because ; the right derivative is nonnegative because . This is a minimum. If , take . There and the active branch has except for the endpoint tie; its derivative vanishes. Convexity again proves the global minimum. The formulas agree at the boundary.
For a fully specified optimal algorithm, compute and once, then use the preceding acceptance test with and . At an integer tie either maximizing integer gives the same test. In code, factorials can be evaluated through the logarithm of the gamma function:and acceptance is . This avoids overflowing factorials.
The optimum minimizes expected trials, the usual idealization of time when each proposal and test has constant cost. Actual runtime also depends on the implementation of discrete inversion and factorial evaluation. Simply minimizing an upper bound for would not necessarily give the exact optimum above; see optimal geometric envelope for a Poisson distribution.
Because , the conditional acceptance probability is , even when the printed threshold exceeds one. Repeating rejected trials gives the clipped acceptance reweighting identity:For , , including . The denominator is , soFor every proposal is accepted, so reweighting by would be incorrect. At both formulas agree. Termination has probability one since the acceptance probability is in the first case and one in the second.
Define . Given , the direct-return branch has probability , while the fallback branch distributes its remaining mass uniformly over . The law of total probability therefore gives, for integer ,The summation includes : a failed direct-return test can still return through the discrete uniform distribution draw. There is no rejection loop and no additional normalization. Summing the displayed probability mass function over gives . At , for example, at every ; it does not become one. This is an instance of the accept-or-fallback mixture identity.
Let . Sinceintegration from zero to gives . Letting and imposing unit total probability givesThe probability density function is positive for because . Consequently the cumulative distribution function is increasing, starts at zero and tends to one. This verifies that the derived normalizing constant defines a probability distribution. The family is the exponential-logarithmic distribution with the complementary mixing parameter .
Solving gives . Hence the quantile function isFor such , , making the logarithm's argument lie in and the output positive. Its endpoint limits are and . Substitution into (i)'s cumulative distribution function recovers .
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
A numerical power series evaluation needs a stopping rule. For and integer , the absolute remainder after terms satisfies the polylogarithm series remainder boundIndeed for , and the remaining powers sum as a geometric series. This also covers negative . The code sums terms in vectors of at most 4096 entries, checking the bound after each block; there is no loop over individual terms.
polylog <- function(a, z, tol = 1e-10, max_terms = 1000000) {
scalar <- function(v) {
is.numeric(v) && !is.complex(v) && length(v) == 1L &&
is.finite(v)
}
if (!scalar(a) || a < 0 || a != floor(a))
stop("a must be a nonnegative integer")
if (!scalar(z) || abs(z) >= 1)
stop("z must be real with abs(z) < 1")
if (!scalar(tol) || tol <= 0 || tol >= 1)
stop("tol must lie strictly between 0 and 1")
if (!scalar(max_terms) || max_terms < 1 ||
max_terms != floor(max_terms))
stop("max_terms must be a positive integer")
if (z == 0) return(0)
r <- abs(z)
N <- 0
ans <- 0
repeat {
if (N >= max_terms)
stop("requested truncation tolerance not reached")
B <- min(4096, max_terms - N)
k <- seq.int(N + 1, N + B)
ans <- ans + sum(z^k * exp(-a * log(k)))
N <- N + B
log_bound <- (N + 1) * log(r) - a * log(N + 1) - log1p(-r)
if (log_bound <= log(tol)) return(ans)
}
}This accepts every positive integer order in the question, and also order zero if is the convention adopted. The bound controls absolute truncation error; floating-point rounding is a separate source of error. Close to , convergence can be slow. If the resource limit is reached, the function reports failure instead of silently claiming the requested accuracy. Useful exact checks are and .
Let and , evaluated from the given polylogarithm formulas. Generate a large sample of independent and identically distributed random variables with
r_sample_f, and compute its sample mean and sample variance using mean and var. The central limit theorem gives the first standardized check:For the second check, the correct asymptotic variance of the sample variance involves the fourth central moment :The denominator is not unless the probability distribution has the requisite fourth central moment, as does the normal distribution. Here the probability density function decays exponentially, so all required moments are finite.To compute , expand the denominator of the probability density function as a geometric series and integrate each nonnegative term. The gamma function integral gives the raw momentsThus and . The following R code implements both checks for chosen interior parameters and large
n:p <- 0.4
beta <- 1.3
n <- 100000
raw_m <- vapply(1:4, function(j) {
-factorial(j) * polylog(j + 1, 1 - p) / (beta^j * log(p))
}, numeric(1))
m <- raw_m[1]
v <- raw_m[2] - m^2
mu4 <- raw_m[4] - 4 * m * raw_m[3] +
6 * m^2 * raw_m[2] - 3 * m^4
x <- r_sample_f(n, p, beta)
c(mean_check = sqrt(n) * (mean(x) - m) / sqrt(v),
variance_check = sqrt(n) * (var(x) - v) / sqrt(mu4 - v^2))For each check separately, an absolute value below is consistent with its approximate confidence interval. Repeat with many independent samples: the two standardized statistics should each resemble a standard normal distribution, with about outside that range. Also vary , and
n; a systematic discrepancy that grows with suggests a bias. The two checks from the same sample are generally dependent, so passing both is not itself a joint statement, nor can a finite test prove that a generator is correct.The second central limit theorem follows from the central limit theorem for the sample variance: differs by a quantity tending to zero in probability from .
Taking the logarithm of the normalized probability density function, then summing over the independent observations, gives the log-likelihoodBoth and are parameters being inferred, so their contributions to the normalizing constant must be retained. The following R implementation validates the arguments and returns one number:
ll_f <- function(p, beta, x) {
scalar <- function(v) {
is.numeric(v) && !is.complex(v) && length(v) == 1L &&
is.finite(v)
}
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 (!is.numeric(x) || is.complex(x) || !is.null(dim(x)) ||
any(!is.finite(x)) || any(x <= 0))
stop("x must be a vector of finite positive numbers")
if (length(x) == 0L) return(0)
t <- log1p(-p) - beta * x
length(x) * (log(beta) - log(-log(p))) +
sum(t - log(-expm1(t)))
}Here and
-expm1(t) computes accurately near zero. The empty-data likelihood function is one, so its log-likelihood is zero. Invalid parameter values produce errors in this evaluator; the next algorithm rejects candidates outside the parameter support before calling it. Articles were limited to the first 100 out of 103 total.
Articles by others on the same topic
There are currently no matching articles.
