The R Project SVN R

Rev

Rev 90027 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/base/man/Random.Rd
68948 ripley 2
% Part of the R package, https://www.R-project.org
90299 maechler 3
% Copyright 1995-2026 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
2 r 6
\name{Random}
56186 murdoch 7
\alias{Random}
3076 pd 8
\alias{RNG}
9
\alias{RNGkind}
23377 pd 10
\alias{RNGversion}
7732 ripley 11
\alias{set.seed}
33493 ripley 12
\alias{.Random.seed}
15168 pd 13
\title{Random Number Generation}
2 r 14
\description{
7081 pd 15
  \code{.Random.seed} is an integer vector, containing the random number
85550 hornik 16
  generator (\abbr{RNG}) \bold{state} for random number generation in \R.  It
7799 maechler 17
  can be saved and restored, but should not be altered by the user.
3076 pd 18
 
19
  \code{RNGkind} is a more friendly interface to query or set the kind
7660 ripley 20
  of RNG in use.
21
 
23377 pd 22
  \code{RNGversion} can be used to set the random generators as they
25099 hornik 23
  were in an earlier \R version (for reproducibility).
46400 ripley 24
 
7790 ripley 25
  \code{set.seed} is the recommended way to specify seeds.
2 r 26
}
15168 pd 27
\usage{
54653 ripley 28
\special{.Random.seed <- c(rng.kind, n1, n2, \dots)}
15168 pd 29
 
90299 maechler 30
RNGkind(kind = NULL, normal.kind = NULL, sample.kind = NULL, binom.kind = NULL)
23377 pd 31
RNGversion(vstr)
90299 maechler 32
set.seed(seed, kind = NULL, normal.kind = NULL, sample.kind = NULL, binom.kind = NULL)
15168 pd 33
}
3076 pd 34
\arguments{
8204 ripley 35
  \item{kind}{character or \code{NULL}.  If \code{kind} is a character
46398 ripley 36
    string, set \R's RNG to the kind desired.  Use \code{"default"} to
37
    return to the \R default.  See \sQuote{Details} for the
47143 ripley 38
    interpretation of \code{NULL}.}
7799 maechler 39
  \item{normal.kind}{character string or \code{NULL}.  If it is a character
46398 ripley 40
    string, set the method of Normal generation.  Use \code{"default"}
41
    to return to the \R default.  \code{NULL} makes no change.}
76160 luke 42
  \item{sample.kind}{character string or \code{NULL}.  If it is a character
43
    string, set the method of discrete uniform generation (used in 
44
    \code{\link{sample}}, for instance).  Use \code{"default"} to return to 
45
    the \R default.  \code{NULL} makes no change.}
90299 maechler 46
  \item{binom.kind}{character string or \code{NULL}.  If it is a character
47
    string, set the method of \code{\link{rbinom}()}.  Use \code{"default"} to return to
48
    the \R default.  \code{NULL} makes no change.}
62311 ripley 49
  \item{seed}{a single value, interpreted as an integer, or \code{NULL}
50
    (see \sQuote{Details}).}
23377 pd 51
  \item{vstr}{a character string containing a version number,
76205 hornik 52
    e.g., \code{"1.6.2"}.  The default RNG configuration of the current
53
    \R version is used if \code{vstr} is greater than the current version.} 
7081 pd 54
  \item{rng.kind}{integer code in \code{0:k} for the above \code{kind}.}
46400 ripley 55
  \item{n1, n2, \dots}{integers.  See the details for how many are required
7081 pd 56
    (which depends on \code{rng.kind}).}
3076 pd 57
}
49649 ripley 58
%% source and more detailed references:  ../../../main/RNG.c
3076 pd 59
\details{
7799 maechler 60
  The currently available RNG kinds are given below.  \code{kind} is
61
  partially matched to this list.  The default is
23384 pd 62
  \code{"Mersenne-Twister"}.
7790 ripley 63
  \describe{
64
    \item{\code{"Wichmann-Hill"}}{
7081 pd 65
    The seed, \code{.Random.seed[-1] == r[1:3]} is an integer vector of
66
    length 3, where each \code{r[i]} is in \code{1:(p[i] - 1)}, where
90027 hornik 67
    \code{p} is the length 3 vector of primes,
68
    \code{p = c(30269, 30307, 30323)}.
85953 hornik 69
    The \I{Wichmann}--\I{Hill} generator has a cycle length of
7790 ripley 70
    \eqn{6.9536 \times 10^{12}}{6.9536e12} (=
88500 hornik 71
    \code{prod(p-1)/4}, see
72
    \bibcitet{R:Wichmann+Hill:1984}
73
    which corrects the original article).
85925 hornik 74
    It exhibits 12 clear failures in the \I{TestU01} Crush suite and 22
88500 hornik 75
    in the \I{BigCrush} suite \bibcitep{R:L_Ecuyer+Simard:2007}.}
7799 maechler 76
 
7790 ripley 77
    \item{\code{"Marsaglia-Multicarry"}:}{
7081 pd 78
    A \emph{multiply-with-carry} RNG is used, as recommended by George
88500 hornik 79
    \I{Marsaglia} in his post to the mailing list \file{sci.stat.math}
80
    \bibcitep{R:Marsaglia:1997}.
80840 maechler 81
    It has a period of more than \eqn{2^{60}}{2^60}.
3076 pd 82
 
85953 hornik 83
    It exhibits 40 clear failures in \I{L'Ecuyer}'s \I{TestU01} Crush suite.
84
    Combined with \I{Ahrens}-\I{Dieter} or \I{Kinderman}-\I{Ramage} it exhibits
80840 maechler 85
    deviations from normality even for univariate distribution
86
    generation.  See \PR{18168} for a discussion.
87
 
88
    The seed is two integers (all values allowed).}
89
 
7790 ripley 90
    \item{\code{"Super-Duper"}:}{
85953 hornik 91
    \I{Marsaglia}'s famous Super-Duper from the 70's.  This is the original
92
    version which does \emph{not} pass the \I{MTUPLE} test of the \I{Diehard}
7081 pd 93
    battery.  It has a period of \eqn{\approx 4.6\times 10^{18}}{about
7799 maechler 94
      4.6*10^18} for most initial seeds.  The seed is two integers (all
7081 pd 95
    values allowed for the first seed: the second must be odd).
7799 maechler 96
 
88500 hornik 97
    We use the implementation by \bibcitet{R:Reeds+Hubert+Abrahams:1982-4}.
7799 maechler 98
 
85977 hornik 99
    The two seeds are the \I{Tausworthe} and congruence long integers,
85835 ripley 100
    respectively.
7799 maechler 101
 
85953 hornik 102
    It exhibits 25 clear failures in the \I{TestU01} Crush suite
90299 maechler 103
    \bibcitep{R:L_Ecuyer+Simard:2007}.
80840 maechler 104
    }
105
 
62069 hornik 106
    \item{\code{"Mersenne-Twister"}:}{
88500 hornik 107
      From \bibcitet{R:Matsumoto+Nishimura:1998}; code updated in 2002.
85925 hornik 108
      A twisted \abbr{GFSR} with period
18519 ripley 109
      \eqn{2^{19937} - 1}{2^19937 - 1} and equidistribution in 623
42961 ripley 110
      consecutive dimensions (over the whole period).  The \sQuote{seed} is a
18519 ripley 111
      624-dimensional set of 32-bit integers plus a current position in
112
      that set.
75569 luke 113
 
114
      R uses its own initialization method due to B. D. Ripley and is
115
      not affected by the initialization issue in the 1998 code of
85953 hornik 116
      \I{Matsumoto} and \I{Nishimura} addressed in a 2002 update.
80840 maechler 117
 
88500 hornik 118
      It exhibits 2 clear failures in each of the \I{TestU01} Crush and
119
      the \I{BigCrush} suite \bibcitep{R:L_Ecuyer+Simard:2007}.
18519 ripley 120
    }
7799 maechler 121
 
62069 hornik 122
    \item{\code{"Knuth-TAOCP-2002"}:}{
85925 hornik 123
      A 32-bit integer \abbr{GFSR} using lagged Fibonacci sequences with
42261 ripley 124
      subtraction.  That is, the recurrence used is
18519 ripley 125
      \deqn{X_j = (X_{j-100} - X_{j-37}) \bmod 2^{30}%
126
      }{X[j] = (X[j-100] - X[j-37]) mod 2^30}
42961 ripley 127
      and the \sQuote{seed} is the set of the 100 last numbers (actually
18519 ripley 128
      recorded as 101 numbers, the last being a cyclic shift of the
129
      buffer).  The period is around \eqn{2^{129}}{2^129}.
42261 ripley 130
    }
46400 ripley 131
 
62069 hornik 132
    \item{\code{"Knuth-TAOCP"}:}{
88591 hornik 133
      An earlier version from \bibcitet{R:Knuth:1997:v2}.
46400 ripley 134
 
42261 ripley 135
      The 2002 version was not backwards compatible with the earlier
85925 hornik 136
      version: the initialization of the \abbr{GFSR} from the seed was altered.
42261 ripley 137
      \R did not allow you to choose consecutive seeds, the reported
80840 maechler 138
      \sQuote{weakness}, and already scrambled the seeds. Otherwise,
85953 hornik 139
      the algorithm is identical to \I{Knuth-TAOCP-2002}, with the same
80840 maechler 140
      lagged Fibonacci recurrence formula.
42547 ripley 141
 
142
      Initialization of this generator is done in interpreted \R code
143
      and so takes a short but noticeable time.
80840 maechler 144
 
85925 hornik 145
      It exhibits 3 clear failure in the \I{TestU01} Crush suite and
146
      4 clear failures in the \I{BigCrush} suite
88500 hornik 147
      \bibcitep{R:L_Ecuyer+Simard:2007}.
18519 ripley 148
    }
62069 hornik 149
    \item{\code{"L'Ecuyer-CMRG"}:}{
88462 hornik 150
      A \sQuote{combined multiple-recursive generator} from
151
      \bibcitet{R:L_Ecuyer:1999},
152
      each element of which is a feedback multiplicative
56570 ripley 153
      generator with three integer elements: thus the seed is a (signed)
154
      integer vector of length 6. The period is around
155
      \eqn{2^{191}}{2^191}.
18519 ripley 156
 
56570 ripley 157
      The 6 elements of the seed are internally regarded as 32-bit
158
      unsigned integers.  Neither the first three nor the last three
159
      should be all zero, and they are limited to less than
160
      \code{4294967087} and \code{4294944443} respectively.
61433 ripley 161
 
56570 ripley 162
      This is not particularly interesting of itself, but provides the
163
      basis for the multiple streams used in package \pkg{parallel}.
164
      % See \code{\link{RngStream}}.
80840 maechler 165
 
88500 hornik 166
      It exhibits 6 clear failures in each of the \I{TestU01} Crush and
167
      the \I{BigCrush} suite \bibcitep{R:L_Ecuyer+Simard:2007}.
56570 ripley 168
    }
169
 
62069 hornik 170
    \item{\code{"user-supplied"}:}{
55555 ripley 171
      Use a user-supplied generator.  See \code{\link{Random.user}} for
42261 ripley 172
      details.
7842 ripley 173
    }
3076 pd 174
  }
7799 maechler 175
 
47402 ripley 176
  \code{normal.kind} can be \code{"Kinderman-Ramage"},
177
  \code{"Buggy Kinderman-Ramage"} (not for \code{set.seed}),
178
  \code{"Ahrens-Dieter"}, \code{"Box-Muller"}, \code{"Inversion"} (the
179
  default), or \code{"user-supplied"}.  (For inversion, see the
85953 hornik 180
  reference in \code{\link{qnorm}}.)  The \I{Kinderman}-\I{Ramage} generator
66886 maechler 181
  used in versions prior to 1.7.0 (now called \code{"Buggy"}) had several
57176 ripley 182
  approximation errors and should only be used for reproduction of old
47402 ripley 183
  results.  The \code{"Box-Muller"} generator is stateful as pairs of
184
  normals are generated and returned sequentially.  The state is reset
185
  whenever it is selected (even if it is the current normal generator)
186
  and when \code{kind} is changed.
7799 maechler 187
 
76160 luke 188
  \code{sample.kind} can be \code{"Rounding"} or \code{"Rejection"},
189
  or partial matches to these.  The former was the default in versions
190
  prior to 3.6.0:  it made \code{\link{sample}} noticeably non-uniform
191
  on large populations, and should only be used for reproduction of old
90299 maechler 192
  results.  See \PR{17494} for a discussion.
76160 luke 193
 
90299 maechler 194
  \code{binom.kind} can be \code{"Buggy BTPE"} or \code{"BTPE"},
195
  or partial matches to these.  The former was the default in versions
196
  prior to 4.7.0: for large but not very large mean,
197
  \code{\link{rbinom}()}'s acceptance-rejection algorithm accepted
198
  very few \dQuote{outer tail} values it should have rejected, leading to a
199
  very slightly increased distribution tail weight.  See \PR{19049} for more.
200
 
201
 
202
  \code{set.seed()} uses a single integer argument to set as many seeds
7799 maechler 203
  as are required.  It is intended as a simple way to get quite different
7790 ripley 204
  seeds by specifying small integer arguments, and also as a way to get
205
  valid seed sets for the more complicated methods (especially
57176 ripley 206
  \code{"Mersenne-Twister"} and \code{"Knuth-TAOCP"}).  There is no
207
  guarantee that different values of \code{seed} will seed the RNG
62311 ripley 208
  differently, although any exceptions would be extremely rare.  If
209
  called with \code{seed = NULL} it re-initializes (see \sQuote{Note})
210
  as if no seed had yet been set.
46398 ripley 211
 
90299 maechler 212
  The use of \code{kind = NULL}, \code{normal.kind = NULL},
213
  \code{sample.kind = NULL} or \code{binom.kind = NULL} in
46400 ripley 214
  \code{RNGkind} or \code{set.seed} selects the currently-used
46889 ripley 215
  generator (including that used in the previous session if the
216
  workspace has been restored): if no generator has been used it selects
217
  \code{"default"}.
3076 pd 218
}
8334 ripley 219
\note{
56607 ripley 220
  Initially, there is no seed; a new one is created from the current
65147 ripley 221
  time and the process ID when one is required.  Hence different
222
  sessions will give different simulation results, by default.  However,
223
  the seed might be restored from a previous session if a previously
224
  saved workspace is restored.
16060 maechler 225
 
8334 ripley 226
  \code{.Random.seed} saves the seed set for the uniform random-number
15168 pd 227
  generator, at least for the system generators.  It does not
228
  necessarily save the state of other generators, and in particular does
229
  not save the state of the Box--Muller normal generator.  If you want
46400 ripley 230
  to reproduce work later, call \code{set.seed} (preferably with
231
  explicit values for \code{kind} and \code{normal.kind}) rather than
232
  set \code{.Random.seed}.
25685 ripley 233
 
38402 ripley 234
  The object \code{.Random.seed} is only looked for in the user's
25685 ripley 235
  workspace.
46400 ripley 236
 
85550 hornik 237
  Do not rely on randomness of low-order bits from \abbr{RNG}s.  Most of the
46351 ripley 238
  supplied uniform generators return 32-bit integer values that are
239
  converted to doubles, so they take at most \eqn{2^{32}}{2^32} distinct
85953 hornik 240
  values and long runs will return duplicated values (\I{Wichmann}-\I{Hill} is
46351 ripley 241
  the exception, and all give at least 30 varying bits.)
8334 ripley 242
}
2 r 243
\value{
7081 pd 244
  \code{.Random.seed} is an \code{\link{integer}} vector whose first
7842 ripley 245
  element \emph{codes} the kind of RNG and normal generator. The lowest
22051 ripley 246
  two decimal digits are in \code{0:(k-1)}
85550 hornik 247
  where \code{k} is the number of available \abbr{RNG}s.  The hundreds
76160 luke 248
  represent the type of normal generator (starting at \code{0}), and
249
  the ten thousands represent the type of discrete uniform sampler.
1032 maechler 250
 
7842 ripley 251
  In the underlying C, \code{.Random.seed[-1]} is \code{unsigned};
88700 kalibera 252
  therefore in \R \code{.Random.seed[-1]} can be negative or perhaps
253
  \code{\link{NA_integer_}}, due to
27625 ripley 254
  the representation of an unsigned integer by a signed integer.
7799 maechler 255
 
90299 maechler 256
  \code{RNGkind} returns the character vector of the RNG and other kinds
257
  selected \emph{before} the call, invisibly if
76160 luke 258
  either argument is not \code{NULL}.  A type starts a session as the 
259
  default, and is selected either by a call to \code{RNGkind} or by setting
76405 ripley 260
  \code{.Random.seed} in the workspace. (NB: prior to \R 3.6.0 the first
261
  two kinds were returned in a two-element character vector.)
7660 ripley 262
 
46398 ripley 263
  \code{RNGversion} returns the same information as \code{RNGkind} about
264
  the defaults in a specific \R version.
265
 
7660 ripley 266
  \code{set.seed} returns \code{NULL}, invisibly.
2 r 267
}
268
\references{
88500 hornik 269
  \bibinfo{R:Becker+Chambers+Wilks:1988}{footer}{
89404 smeyer 270
    (\code{set.seed}, storing in \code{.Random.seed}.)}
88591 hornik 271
  \bibinfo{R:Knuth:1997:v2}{footer}{
89404 smeyer 272
    Source code at \url{https://www-cs-faculty.stanford.edu/~knuth/taocp.html}.}
88500 hornik 273
  \bibinfo{R:L_Ecuyer+Simard:2007}{footer}{
89404 smeyer 274
    The \I{TestU01} C library is available from
89995 hornik 275
    %% Does not work as of 2026-04-30:
276
    %% \url{https://simul.iro.umontreal.ca/testu01/tu01.html} or also
89404 smeyer 277
    \url{https://github.com/umontreal-simul/TestU01-2009}.
88490 hornik 278
  }
88500 hornik 279
  \bibinfo{R:Matsumoto+Nishimura:1998}{footer}{
89404 smeyer 280
    Source code formerly at \code{http://www.math.keio.ac.jp/~matumoto/emt.html}.
281
    Now see \url{https://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/c-lang.html}.}
88500 hornik 282
  \bibinfo{R:Wichmann+Hill:1982}{note}{Remarks:
89404 smeyer 283
    \bold{34}, 198 and \bold{35}, 89.}
88462 hornik 284
 
88500 hornik 285
  \bibshow{*,
286
    R:Ahrens+Dieter:1973,
287
    R:Becker+Chambers+Wilks:1988,
288
    R:Box+Muller:1958,
289
    R:De_Matteis+Pagnutti:1993,
290
    R:Kinderman+Ramage:1976,
88591 hornik 291
    R:Knuth:2002:v3,
88500 hornik 292
    R:Marsaglia+Zaman:1994,
293
    R:Wichmann+Hill:1982}
2 r 294
}
76160 luke 295
\author{of RNGkind: Martin Maechler. Current implementation, B. D. Ripley
296
  with modifications by Duncan Murdoch.}
3076 pd 297
 
52774 ripley 298
\seealso{
299
  \code{\link{sample}} for random sampling with and without replacement.
61433 ripley 300
 
52774 ripley 301
  \link{Distributions} for functions for random-variate generation from
302
  standard distributions.
303
}
75013 maechler 304
\examples{
41508 ripley 305
require(stats)
306
 
75013 maechler 307
## Seed the current RNG, i.e., set the RNG status
308
set.seed(42); u1 <- runif(30)
309
set.seed(42); u2 <- runif(30) # the same because of identical RNG status:
310
stopifnot(identical(u1, u2))
2 r 311
 
75013 maechler 312
\donttest{## the default random seed is 626 integers, so only print a few
313
 runif(1); .Random.seed[1:6]; runif(1); .Random.seed[1:6]
314
 ## If there is no seed, a "random" new one is created:
315
 rm(.Random.seed); runif(1); .Random.seed[1:6]
316
}
43870 murdoch 317
ok <- RNGkind()
61168 ripley 318
RNGkind("Wich")  # (partial string matching on 'kind')
16060 maechler 319
 
25118 hornik 320
## This shows how 'runif(.)' works for Wichmann-Hill,
16060 maechler 321
## using only R functions:
322
 
2 r 323
p.WH <- c(30269, 30307, 30323)
8204 ripley 324
a.WH <- c(  171,   172,   170)
15168 pd 325
next.WHseed <- function(i.seed = .Random.seed[-1])
326
  { (a.WH * i.seed) \%\% p.WH }
2 r 327
my.runif1 <- function(i.seed = .Random.seed)
3076 pd 328
  { ns <- next.WHseed(i.seed[-1]); sum(ns / p.WH) \%\% 1 }
75013 maechler 329
set.seed(1998-12-04)# (when the next lines were added to the souRce)
2 r 330
rs <- .Random.seed
3076 pd 331
(WHs <- next.WHseed(rs[-1]))
332
u <- runif(1)
8893 maechler 333
stopifnot(
334
 next.WHseed(rs[-1]) == .Random.seed[-1],
335
 all.equal(u, my.runif1(rs))
336
)
3076 pd 337
 
338
## ----
339
.Random.seed
61168 ripley 340
RNGkind("Super") # matches  "Super-Duper"
3076 pd 341
RNGkind()
342
.Random.seed # new, corresponding to  Super-Duper
343
 
344
## Reset:
7766 ripley 345
RNGkind(ok[1])
30059 ripley 346
 
76241 maechler 347
RNGversion(getRversion()) # the default version for this R version
348
 
30059 ripley 349
## ----
46351 ripley 350
sum(duplicated(runif(1e6))) # around 110 for default generator
30059 ripley 351
## and we would expect about almost sure duplicates beyond about
61150 ripley 352
qbirthday(1 - 1e-6, classes = 2e9) # 235,000
75016 ripley 353
}
286 maechler 354
\keyword{distribution}
355
\keyword{sysdata}