srnorm: Sampling from Normal Distribution

View source: R/srnorm.R

srnormR Documentation

Sampling from Normal Distribution

Description

The srnorm() function generates random samples from a Normal distribution using the STORS algorithm. It employs an optimized proposal distribution around the mode and Adaptive Rejection Sampling (ARS) for the tails.

Usage

srnorm(n = 1, mean = 0, sd = 1, x = NULL)

srnorm_custom(n = 1, x = NULL)

Arguments

n

Integer, length 1. Number of samples to draw.

mean

Numeric. Mean parameter of the Normal distribution.

sd

Numeric. Standard deviation of the target Normal distribution.

x

(optional) Numeric vector of length n. If provided, this vector is over written in place to avoid any memory allocation.

Details

The Normal distribution has the probability density function (PDF): f(x | \mu, \sigma) = \frac{1}{\sigma\sqrt{2\pi}} \exp\left(-\frac{(x - \mu)^2}{2\sigma^2}\right), where:

\mu

is the mean of the distribution, which determines the centre of the bell curve.

\sigma

is the standard deviation, which controls the spread of the distribution (\sigma > 0).

These two functions are for sampling using the STORS algorithm based on the proposal that has been constructed using srnorm_optimize.

By default, srnorm() samples from a standard Normal distribution (mean = 0, sd = 1). The proposal distribution is pre-optimized at package load time using srnorm_optimize() with steps = 4091, creating a scalable proposal centred around the mode.

If srnorm() is called with custom mean or sd parameters, the samples are generated from the standard Normal distribution, then scaled and location shifted accordingly.

Value

A numeric vector of length n containing samples from the Normal distribution with the specified mean and sd.

NOTE: When the x parameter is specified, it is updated in-place with the simulation for performance reasons.

See Also

srnorm_optimize to optimize the custom or the scaled proposal.

Examples

# Generate 10 samples from the standard Normal distribution
samples <- srnorm(10)
print(samples)

# Generate 10 samples using a pre-allocated vector
x <- numeric(10)
srnorm(10, x = x)
print(x)

# Generate 10 samples from a Normal distribution with mean = 2 and sd = 3
samples <- srnorm(10, mean = 2, sd = 3)
print(samples)


stors documentation built on April 3, 2025, 6:16 p.m.