None of the answers here give an efficient method of generating truncated normal variables that does not involve rejection of arbitrarily large numbers of generated values. If you want to generate values from a truncated normal distribution, with specified lower and upper bounds $a<b$, this can be done ---without rejection--- by generating uniform quantiles over the quantile range allowed by the truncation, and using inverse transformation sampling to get corresponding normal values.
Let $\Phi$ denote the CDF of the standard normal distribution. We want to generate $X_1,...,X_N$ from a truncated normal distribution (with mean parameter $\mu$ and variance parameter $\sigma^2$)$^\dagger$ with lower and upper truncation bounds $a<b$. This can be done as follows:
$$X_i = \mu + \sigma \cdot \Phi^{-1}(U_i) \quad \quad \quad
U_1,...,U_N \sim \text{IID U} \Big[ \Phi \Big( \frac{a-\mu}{\sigma} \Big), \Phi \Big( \frac{b-\mu}{\sigma} \Big) \Big].$$
There is no inbuilt function for generated values from the truncated distribution, but it is trivial to program this method using the ordinary functions for generating random variables. Here is a simple R
function rtruncnorm
that implements this method in a few lines of code.
rtruncnorm <- function(N, mean = 0, sd = 1, a = -Inf, b = Inf) {
if (a > b) stop('Error: Truncation range is empty');
U <- runif(N, pnorm(a, mean, sd), pnorm(b, mean, sd));
qnorm(U, mean, sd); }
This is a vectorised function that will generate N
IID random variables from the truncated normal distribution. It would be easy to program functions for other truncated distributions via the same method. It would also not be too difficult to program associated density and quantile functions for the truncated distribution.
$^\dagger$ Note that the truncation alters the mean and variance of the distribution, so $\mu$ and $\sigma^2$ are not the mean and variance of the truncated distribution.
x <- rnorm(n, mean, sd); x <- x[x > lower.limit & x < upper.limit]
$\endgroup$ – Hugh Aug 26 '14 at 10:31