Skip to content

Instantly share code, notes, and snippets.

@tomhopper
Last active August 18, 2023 03:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhopper/19f07fc96db8d149b24f to your computer and use it in GitHub Desktop.
Save tomhopper/19f07fc96db8d149b24f to your computer and use it in GitHub Desktop.
Functions to create normally distributed data between two values minimum and maximum. One function pegs the minimum and maximum; the other uses a 99.7% tolerance interval.
#' @title Returns a normally distributed vector within the 99.7% tolerance interval defined by minimum and maximum
#' @param n (required) The number of random numbers to generate
#' @param minimum (optional) The lower 99.9% tolerance limit
#' @param maximum (optional) The upper 99.9% tolerance limit
#' @return numeric vector with n elements randomly distributed so that approximately 99.7% of values will fall between minimum and maximum
#' @examples
#' rnorm.within(10)
#' rnorm.within(10, 10, 20)
#' summary(rnorm.within(10000, 10, 20))
rnorm.within <- function(n, minimum=0, maximum=1)
{
x <- rnorm(n, mean = 0, sd = 1)
x <- x - -3
x <- x / (6)
x <- x * (maximum - minimum)
x <- x + minimum
return(x)
}
#' @title Returns a normally distributed vector between minimum and maximum
#' @param n (required) The number of random numbers to generate
#' @param minimum (optional) The minimum value to return
#' @param maximum (optional) The maximum value to return
#' @return numeric vector with n elements randomly distributed between minimum and maximum
#' @examples
#' rnorm.between(10)
#' rnorm.between(10, 10, 20)
#' summary(rnorm.between(10000, 10, 20))
rnorm.between <- function(n, minimum = 0, maximum = 1)
{
x <- rnorm(n)
max_x <- max(x)
min_x <- min(x)
x <- x - min_x
x <- x / (max_x - min_x)
x <- x * (maximum - minimum)
x <- x + minimum
return(x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment