Debian Codegraph @

R/algorithm.R

raw
1 #' Pseudo-random numbers on `[0, 1)` based on a linear congruential generator
2 #'
3 #' Generate pseudo-random numbers from \eqn{X_{i+1} = (aX_i + c) \bmod{m}}{X[i +
4 #' 1] = (a * X[i] + c) %% m}, where \eqn{X_1}{X[1]} is the initial value (seed).
5 #' @param n The desired length of the sequence.
6 #' @param a,c,m Parameters for the generator (see References for the default
7 #' values).
8 #' @param seed The seed. The default is the system time when this function is
9 #' called for the first time in the current session. For subsequent calls, the
10 #' last \eqn{X_i}{X[i]} of the previous call will be used as the default seed.
11 #' @return Random numbers on `[0, 1)` (i.e., \eqn{X/m} instead of \eqn{X}). Note
12 #' the unit interval is open on the right (excluding 1).
13 #' @note All argument values must be smaller than \eqn{2^{64}}{2^64} as they
14 #' will be coerced to 64-bit integers.
15 #' @references Steele, Guy L. Jr.; Vigna, Sebastiano (2022). "Computationally
16 #' easy, spectrally good multipliers for congruential pseudorandom number
17 #' generators". _Software: Practice and Experience._ 52 (2): 443–458.
18 #' @export
19 #' @examples
20 #' rand_unit(10)
21 #' rand_unit(10, seed = 0)
22 #' rand_unit(10, seed = 0) # identical results
23 #' rand_unit(10, seed = Sys.getpid())
24 rand_unit = local({
25 .seed = NULL
26 function(n = 1, a = 0xd9f5, c = 0, m = 4294967296, seed = NULL) {
27 .seed <<- seed %||% .seed %||% as.numeric(Sys.time())
28 x = .Call('rand_lcg', n, .seed, a, c, m, PACKAGE = 'xfun')
29 if (n > 0) .seed <<- x[n]
30 x / m
31 }
32 })
33
34 # n random integers from 1 to M
35 rand_n = function(n, M) floor(rand_unit(n) * M) + 1