rnormal-distribution

Generating a normally distributed random variable that has range [1, 3] in R


I want to generate a normally distributed random variable that has range [1, 3].

Specifically, I tried the following R code:

x1 <- runif(100, 1, 2)
x2 <- rnorm(100, 0, 0.3)

V <- 1 + x1 + x2

Then, V follows a normal distribution (conditional on x1) and is roughly concentrated on [1, 3].

But, I want to make V to have range [1, 3]. That is, all elements should be in [1, 3], not roughly on [1, 3]:

min(V)
[1] 1
max(V)
[1] 3

I have no idea how to do. Is there a technique for this task?


Solution

  • Since the support of any normal distribution is the whole real number line, the only way to get what you are looking for is to draw a sample and then normalize it into your specified range. As r2evans points out, there are theoretical problems with any such approach. However, a simple implementation of it would be

    rnorm_limits <- function(n, min = 1, max = 3) {
      x <- rnorm(n)
      x <- (max - min) * x/diff(range(x))
      return(x - min(x) + min)
    }
    

    Testing, we have:

    set.seed(1)
    
    hist(rnorm_limits(100))
    

    And of course the range will be exactly that specified:

    range(rnorm_limits(100))
    #> [1] 1 3