If you need only a few truly random numbers you might use dice or atmospheric noise. However, if you need many random numbers you will have to use a pseudo random number generator (RNG). R includes support for different RNGs (c.f.
?Random) and a wide variety of distributions (c.f.
?distributions). The underlying methods have been well tested, but faster methods are available. The dqrng package provides fast random number generators with good statistical properties for usage with R. It combines these RNGs with fast distribution functions to sample from uniform, normal or exponential distributions.
At the moment dqrng is not on CRAN, but you can install the current version via drat:
if (!requireNamespace("drat", quietly = TRUE)) install.packages("drat") drat::addRepo("daqana") install.packages("dqrng")
Using the provided RNGs from R is deliberately similar to using R’s build-in RNGs:
library(dqrng) dqRNGkind("Xoroshiro128+") dqset.seed(42) dqrunif(5, min = 2, max = 10) ##  4.498747 9.500660 2.457009 5.249195 2.370585 dqrnorm(5, mean = 3, sd = 5) ##  5.748100 -4.368370 -1.231515 -7.552863 8.959892 dqrexp(5, rate = 4) ##  0.002043171 0.261604407 0.132934079 0.048892818 0.549762841
They are quite a bit faster, though, as we can see by comparing 10 million random draws from different distributions:
N <- 1e7 tm <- microbenchmark( runif = runif(N), dqrunif = dqrunif(N), rnorm = rnorm(N), dqrnorm = dqrnorm(N), rexp = rexp(N), dqrexp = dqrexp(N))
r* the default Mersenne-Twister was used, while
dqr* used Xoroshiro128+ in this comparison. For
rnorm the default inversion method was used, while
dqrexp) used the Ziggurat algorithm from Boost.Random with additional tuning.
Supported Random Number Generators
Support for the following 64 bit RNGs is currently included:
The 64 bit variant of the well-known Mersenne-Twister, which is also used as default. This is a conservative default that allows you to take advantage of the fast distribution functions provided by dqrng while staying close to R’s default RNG (32 bit Mersenne-Twister).
The default 64 bit variant from the PCG family developed by Melissa O’Neill. See http://www.pcg-random.org for more details.
- Xoroshiro128+, Xorshift128+, and Xorshift1024*