this set of functions generates random bytes or numbers from OpenSSL. This
provides a cryptographically secure alternative to R's default random number generator.
rand_bytes generates n random cryptographically secure bytes
rand_bytes(n = 1)
rand_num(n = 1)OpenSSL manual: https://docs.openssl.org/1.1.1/man3/RAND_bytes/
rnd <- rand_bytes(10)
as.numeric(rnd)
#> [1] 25 40 244 146 81 244 134 33 134 13
as.character(rnd)
#> [1] "19" "28" "f4" "92" "51" "f4" "86" "21" "86" "0d"
as.logical(rawToBits(rnd))
#> [1] TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
#> [13] FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE TRUE TRUE TRUE TRUE
#> [25] FALSE TRUE FALSE FALSE TRUE FALSE FALSE TRUE TRUE FALSE FALSE FALSE
#> [37] TRUE FALSE TRUE FALSE FALSE FALSE TRUE FALSE TRUE TRUE TRUE TRUE
#> [49] FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE
#> [61] FALSE TRUE FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE
#> [73] TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE
# bytes range from 0 to 255
rnd <- rand_bytes(100000)
hist(as.numeric(rnd), breaks=-1:255)
# Generate random doubles between 0 and 1
rand_num(5)
#> [1] 0.2742019 0.4605483 0.1639707 0.1987847 0.2633428
# Use CDF to map [0,1] into random draws from a distribution
x <- qnorm(rand_num(1000), mean=100, sd=15)
hist(x)
y <- qbinom(rand_num(1000), size=10, prob=0.3)
hist(y)