rwm_norm: Univariate Random Walk Metropolis with Normal Proposal

View source: R/randwalk_Metropolis.R

rwm_normR Documentation

Univariate Random Walk Metropolis with Normal Proposal

Description

Single update for the univariate random-walk Metropolis sampler with a normal proposal distribution.

Usage

rwm_norm(x, log_target, cand_sd, support = c(-Inf, Inf), diagnostics = NULL)

Arguments

x

The current state (as a numeric scalar).

log_target

A function taking numeric scalar that evaluates the (potentially unnormalized) log-target density, returning a numeric scalar.

cand_sd

A positive numeric scalar tuning the algorithm. Gives the standard deviation of the normal random-walk proposal.

support

Numeric vector of length two giving the lower and upper boundaries of the support for the target distribution. Default is c(-Inf, Inf), in which case the target density will always be evaluated at the proposed value.

diagnostics

Logical, indicating whether the sampler should be run in diagnostic mode for informative error handling. When diagnostics is NULL, it is reset to match the value of getOption("qslice.diagnostics") which defaults to FALSE if the option is not set. Default for diagnostics is NULL.

Value

A list with three elements:

x is the new state.

accept Logical indicating whether the proposal was accepted.

nEvaluations is the number of evaluations of the target function used to obtain the new state.

Examples

lf <- function(x) dbeta(x, 3, 4, log = TRUE)
draws <- numeric(10) + 0.5 # set to numeric(1e3) for more complete illustration
nEvaluations <- 0L
nAccept <- 0L
for (i in seq.int(2, length(draws))) {
  out <- rwm_norm(draws[i - 1], log_target = lf, cand_sd = 0.3, support = c(0.0, 1.0))
  draws[i] <- out$x
  nEvaluations <- nEvaluations + out$nEvaluations
  nAccept <- nAccept + out$accept
}
nEvaluations / (length(draws) - 1)
nAccept / (length(draws) - 1)
plot(density(draws), xlim = c(0, 1))
curve(exp(lf(x)), 0, 1, col = "blue", add = TRUE)


qslice documentation built on Oct. 22, 2026, 1:06 a.m.