Learn R Programming

ggdmcPrior (version 0.2.9.0)

tnorm: Truncated Normal Distribution Functions

Description

Density, distribution function, and random number generation for the truncated normal distribution with mean p0, standard deviation p1, and truncation bounds [lower, upper].

Usage

rtnorm(n, p0, p1, lower, upper)

ptnorm(x, p0, p1, lower, upper, lower_tail, log_p = FALSE)

dtnorm(x, p0, p1, lower, upper, log_p = FALSE)

Value

rtnorm

A numeric vector of length n, containing random variates from the truncated normal distribution.

ptnorm

A numeric vector of cumulative probabilities evaluated at x.

dtnorm

A numeric vector of (log) density values evaluated at x.

Arguments

n

Integer. Number of random variates to generate (for rtnorm).

p0

Mean of the underlying (untruncated) normal distribution.

p1

Standard deviation of the underlying normal distribution. Must be positive.

lower

Lower bound of truncation (can be -Inf).

upper

Upper bound of truncation (can be Inf).

x

Numeric vector of quantiles (for dtnorm and ptnorm).

lower_tail

Logical; if TRUE (default), probabilities are computed as \(P[X \leq x]\), otherwise \(P[X > x]\).

log_p

Logical; if TRUE, probabilities or densities are returned on the log scale.

Details

These functions implement the truncated normal distribution:

  • rtnorm: Generates random samples using inverse transform sampling.

  • ptnorm: Computes the cumulative distribution function (CDF).

  • dtnorm: Computes the probability density function (PDF).

The truncated normal distribution is defined as: $$X \sim \mathcal{N}(\mu, \sigma^2), \quad \text{truncated to } [a, b]$$ where \(\mu = \code{p0}\), \(\sigma = \code{p1}\), \(a = \code{lower}\), and \(b = \code{upper}\).

Truncation can be one-sided (e.g., lower = 0, upper = Inf) or two-sided.

References

Examples

Run this code
# Generate random samples from truncated normal
n <- 1e5
p0 <- 0
p1 <- 1
lower <- 0
upper <- Inf
rtnorm_dat <- rtnorm(n, p0, p1, lower, upper)

# Density at quantiles
x <- seq(-5, 5, length.out = 1e3)
dtnorm_dat <- dtnorm(x, p0, p1, lower = -2, upper = 2, log_p = FALSE)

# Cumulative probabilities
q <- seq(-5, 5, length.out = 1e3)
ptnorm_dat <- ptnorm(q, p0, p1, lower = -2, upper = 3, 
                     lower_tail = TRUE, log_p = FALSE)

# Plotting
cex_lab <- 1
cex_axis <- 0.5
line_width <- 1.5

hist(rtnorm_dat, breaks = "fd", freq = FALSE, xlab = "", 
     cex.lab = cex_lab, cex.axis = cex_axis, main = "")
plot(x, dtnorm_dat, type = "l", lwd = line_width, xlab = "",
     ylab = "Density", cex.lab = cex_lab, cex.axis = cex_axis, main = "")

Run the code above in your browser using DataLab