📄 rng.texi
字号:
@cindex random number generators
The library provides a large collection of random number generators
which can be accessed through a uniform interface. Environment
variables allow you to select different generators and seeds at runtime,
so that you can easily switch between generators without needing to
recompile your program. Each instance of a generator keeps track of its
own state, allowing the generators to be used in multi-threaded
programs. Additional functions are available for transforming uniform
random numbers into samples from continuous or discrete probability
distributions such as the Gaussian, log-normal or Poisson distributions.
These functions are declared in the header file @file{gsl_rng.h}.
@comment Need to explain the difference between SERIAL and PARALLEL random
@comment number generators here
@menu
* General comments on random numbers::
* The Random Number Generator Interface::
* Random number generator initialization::
* Sampling from a random number generator::
* Auxiliary random number generator functions::
* Random number environment variables::
* Copying random number generator state::
* Reading and writing random number generator state::
* Random number generator algorithms::
* Unix random number generators::
* Other random number generators::
* Random Number Generator Performance::
* Random Number Generator Examples::
* Random Number References and Further Reading::
* Random Number Acknowledgements::
@end menu
@node General comments on random numbers
@section General comments on random numbers
In 1988, Park and Miller wrote a paper entitled ``Random number
generators: good ones are hard to find.'' [Commun. ACM, 31, 1192--1201].
Fortunately, some excellent random number generators are available,
though poor ones are still in common use. You may be happy with the
system-supplied random number generator on your computer, but you should
be aware that as computers get faster, requirements on random number
generators increase. Nowadays, a simulation that calls a random number
generator millions of times can often finish before you can make it down
the hall to the coffee machine and back.
A very nice review of random number generators was written by Pierre
L'Ecuyer, as Chapter 4 of the book: Handbook on Simulation, Jerry Banks,
ed. (Wiley, 1997). The chapter is available in postscript from
L'Ecuyer's ftp site (see references). Knuth's volume on Seminumerical
Algorithms (originally published in 1968) devotes 170 pages to random
number generators, and has recently been updated in its 3rd edition
(1997).
@comment is only now starting to show its age.
@comment Nonetheless,
It is brilliant, a classic. If you don't own it, you should stop reading
right now, run to the nearest bookstore, and buy it.
A good random number generator will satisfy both theoretical and
statistical properties. Theoretical properties are often hard to obtain
(they require real math!), but one prefers a random number generator
with a long period, low serial correlation, and a tendency @emph{not} to
``fall mainly on the planes.'' Statistical tests are performed with
numerical simulations. Generally, a random number generator is used to
estimate some quantity for which the theory of probability provides an
exact answer. Comparison to this exact answer provides a measure of
``randomness''.
@node The Random Number Generator Interface
@section The Random Number Generator Interface
It is important to remember that a random number generator is not a
``real'' function like sine or cosine. Unlike real functions, successive
calls to a random number generator yield different return values. Of
course that is just what you want for a random number generator, but to
achieve this effect, the generator must keep track of some kind of
``state'' variable. Sometimes this state is just an integer (sometimes
just the value of the previously generated random number), but often it
is more complicated than that and may involve a whole array of numbers,
possibly with some indices thrown in. To use the random number
generators, you do not need to know the details of what comprises the
state, and besides that varies from algorithm to algorithm.
The random number generator library uses two special structs,
@code{gsl_rng_type} which holds static information about each type of
generator and @code{gsl_rng} which describes an instance of a generator
created from a given @code{gsl_rng_type}.
The functions described in this section are declared in the header file
@file{gsl_rng.h}.
@node Random number generator initialization
@section Random number generator initialization
@deftypefn Random {gsl_rng *} gsl_rng_alloc (const gsl_rng_type * @var{T})
This function returns a pointer to a newly-created
instance of a random number generator of type @var{T}.
For example, the following code creates an instance of the Tausworthe
generator,
@example
gsl_rng * r = gsl_rng_alloc (gsl_rng_taus);
@end example
If there is insufficient memory to create the generator then the
function returns a null pointer and the error handler is invoked with an
error code of @code{GSL_ENOMEM}.
The generator is automatically initialized with the default seed,
@code{gsl_rng_default_seed}. This is zero by default but can be changed
either directly or by using the environment variable @code{GSL_RNG_SEED}
(@pxref{Random number environment variables}).
The details of the available generator types are
described later in this chapter.
@end deftypefn
@deftypefn Random void gsl_rng_set (const gsl_rng * @var{r}, unsigned long int @var{s})
This function initializes (or `seeds') the random number generator. If
the generator is seeded with the same value of @var{s} on two different
runs, the same stream of random numbers will be generated by successive
calls to the routines below. If different values of @var{s} are
supplied, then the generated streams of random numbers should be
completely different. If the seed @var{s} is zero then the standard seed
from the original implementation is used instead. For example, the
original Fortran source code for the @code{ranlux} generator used a seed
of 314159265, and so choosing @var{s} equal to zero reproduces this when
using @code{gsl_rng_ranlux}.
@end deftypefn
@deftypefn Random void gsl_rng_free (gsl_rng * @var{r})
This function frees all the memory associated with the generator
@var{r}.
@end deftypefn
@node Sampling from a random number generator
@section Sampling from a random number generator
The following functions return uniformly distributed random numbers,
either as integers or double precision floating point numbers. To obtain
non-uniform distributions @pxref{Random Number Distributions}.
@deftypefn Random {unsigned long int} gsl_rng_get (const gsl_rng * @var{r})
This function returns a random integer from the generator @var{r}. The
minimum and maximum values depend on the algorithm used, but all
integers in the range [@var{min},@var{max}] are equally likely. The
values of @var{min} and @var{max} can determined using the auxiliary
functions @code{gsl_rng_max (r)} and @code{gsl_rng_min (r)}.
@end deftypefn
@deftypefn Random double gsl_rng_uniform (const gsl_rng * @var{r})
This function returns a double precision floating point number uniformly
distributed in the range [0,1). The range includes 0.0 but excludes 1.0.
The value is typically obtained by dividing the result of
@code{gsl_rng_get(r)} by @code{gsl_rng_max(r) + 1.0} in double
precision. Some generators compute this ratio internally so that they
can provide floating point numbers with more than 32 bits of randomness
(the maximum number of bits that can be portably represented in a single
@code{unsigned long int}).
@end deftypefn
@deftypefn Random double gsl_rng_uniform_pos (const gsl_rng * @var{r})
This function returns a positive double precision floating point number
uniformly distributed in the range (0,1), excluding both 0.0 and 1.0.
The number is obtained by sampling the generator with the algorithm of
@code{gsl_rng_uniform} until a non-zero value is obtained. You can use
this function if you need to avoid a singularity at 0.0.
@end deftypefn
@deftypefn Random {unsigned long int} gsl_rng_uniform_int (const gsl_rng * @var{r}, unsigned long int @var{n})
This function returns a random integer from 0 to @var{n-1} inclusive.
All integers in the range [0,@var{n-1}] are equally likely, regardless
of the generator used. An offset correction is applied so that zero is
always returned with the correct probability, for any minimum value of
the underlying generator.
If @var{n} is larger than the range of the generator then the function
calls the error handler with an error code of @code{GSL_EINVAL} and
returns zero.
@end deftypefn
@node Auxiliary random number generator functions
@section Auxiliary random number generator functions
The following functions provide information about an existing
generator. You should use them in preference to hard-coding the generator
parameters into your own code.
@deftypefn Random {const char *} gsl_rng_name (const gsl_rng * @var{r})
This function returns a pointer to the name of the generator.
For example,
@example
printf ("r is a '%s' generator\n",
gsl_rng_name (r));
@end example
@noindent
would print something like @code{r is a 'taus' generator}.
@end deftypefn
@deftypefn Random {unsigned long int} gsl_rng_max (const gsl_rng * @var{r})
@code{gsl_rng_max} returns the largest value that @code{gsl_rng_get}
can return.
@end deftypefn
@deftypefn Random {unsigned long int} gsl_rng_min (const gsl_rng * @var{r})
@code{gsl_rng_min} returns the smallest value that @code{gsl_rng_get}
can return. Usually this value is zero. There are some generators with
algorithms that cannot return zero, and for these generators the minimum
value is 1.
@end deftypefn
@deftypefn Random {void *} gsl_rng_state (const gsl_rng * @var{r})
@deftypefnx Random size_t gsl_rng_size (const gsl_rng * @var{r})
These functions return a pointer to the state of generator @var{r} and
its size. You can use this information to access the state directly. For
example, the following code will write the state of a generator to a
stream,
@example
void * state = gsl_rng_state (r);
size_t n = gsl_rng_size (r);
fwrite (state, n, 1, stream);
@end example
@end deftypefn
@deftypefn Random {const gsl_rng_type **} gsl_rng_types_setup (void)
This function returns a pointer to an array of all the available
generator types, terminated by a null pointer. The function should be
called once at the start of the program, if needed. The following code
fragment shows how to iterate over the array of generator types to print
the names of the available algorithms,
@example
const gsl_rng_type **t, **t0;
t0 = gsl_rng_types_setup ();
printf ("Available generators:\n");
for (t = t0; *t != 0; t++)
@{
printf ("%s\n", (*t)->name);
@}
@end example
@end deftypefn
@node Random number environment variables
@section Random number environment variables
The library allows you to choose a default generator and seed from the
environment variables @code{GSL_RNG_TYPE} and @code{GSL_RNG_SEED} and
the function @code{gsl_rng_env_setup}. This makes it easy try out
different generators and seeds without having to recompile your program.
@deftypefun {const gsl_rng_type *} gsl_rng_env_setup (void)
This function reads the environment variables @code{GSL_RNG_TYPE} and
@code{GSL_RNG_SEED} and uses their values to set the corresponding
library variables @code{gsl_rng_default} and
@code{gsl_rng_default_seed}. These global variables are defined as
follows,
@example
extern const gsl_rng_type *gsl_rng_default
extern unsigned long int gsl_rng_default_seed
@end example
The environment variable @code{GSL_RNG_TYPE} should be the name of a
generator, such as @code{taus} or @code{mt19937}. The environment
variable @code{GSL_RNG_SEED} should contain the desired seed value. It
is converted to an @code{unsigned long int} using the C library function
@code{strtoul}.
If you don't specify a generator for @code{GSL_RNG_TYPE} then
@code{gsl_rng_mt19937} is used as the default. The initial value of
@code{gsl_rng_default_seed} is zero.
@end deftypefun
@noindent
Here is a short program which shows how to create a global
generator using the environment variables @code{GSL_RNG_TYPE} and
@code{GSL_RNG_SEED},
@example
@verbatiminclude examples/rng.c
@end example
@noindent
Running the program without any environment variables uses the initial
defaults, an @code{mt19937} generator with a seed of 0,
@example
bash$ ./a.out
@verbatiminclude examples/rng.out
@end example
@noindent
By setting the two variables on the command line we can
change the default generator and the seed,
@example
bash$ GSL_RNG_TYPE="taus" GSL_RNG_SEED=123 ./a.out
GSL_RNG_TYPE=taus
GSL_RNG_SEED=123
generator type: taus
seed = 123
first value = 2720986350
@end example
@node Copying random number generator state
@section Copying random number generator state
The above methods ignore the random number `state' which changes from
call to call. It is often useful to be able to save and restore the
state. To permit these practices, a few somewhat more advanced
functions are supplied. These include:
@deftypefn Random int gsl_rng_memcpy (gsl_rng * @var{dest}, const gsl_rng * @var{src})
This function copies the random number generator @var{src} into the
pre-existing generator @var{dest}, making @var{dest} into an exact copy
of @var{src}. The two generators must be of the same type.
@end deftypefn
@deftypefn Random {gsl_rng *} gsl_rng_clone (const gsl_rng * @var{r})
This function returns a pointer to a newly created generator which is an
exact copy of the generator @var{r}.
@end deftypefn
@node Reading and writing random number generator state
@section Reading and writing random number generator state
The library provides functions for reading and writing the random
number state to a file as binary data or formatted text.
@deftypefun int gsl_rng_fwrite (FILE * @var{stream}, const gsl_rng * @var{r})
This function writes the random number state of the random number
generator @var{r} to the stream @var{stream} in binary format. The
return value is 0 for success and @code{GSL_EFAILED} if there was a
problem writing to the file. Since the data is written in the native
binary format it may not be portable between different architectures.
@end deftypefun
@deftypefun int gsl_rng_fread (FILE * @var{stream}, gsl_rng * @var{r})
This function reads the random number state into the random number
generator @var{r} from the open stream @var{stream} in binary format.
The random number generator @var{r} must be preinitialized with the
correct random number generator type since type information is not
saved. The return value is 0 for success and @code{GSL_EFAILED} if
there was a problem reading from the file. The data is assumed to
have been written in the native binary format on the same
architecture.
@end deftypefun
@node Random number generator algorithms
@section Random number generator algorithms
The functions described above make no reference to the actual algorithm
used. This is deliberate so that you can switch algorithms without
having to change any of your application source code. The library
provides a large number of generators of different types, including
simulation quality generators, generators provided for compatibility
with other libraries and historical generators from the past.
The following generators are recommended for use in simulation. They
have extremely long periods, low correlation and pass most statistical
tests.
@deffn {Generator} gsl_rng_mt19937
@cindex MT19937 random number generator
The MT19937 generator of Makoto Matsumoto and Takuji Nishimura is a
variant of the twisted generalized feedback shift-register algorithm,
and is known as the "Mersenne Twister" generator. It has a Mersenne
prime period of
@comment
@c{$2^{19937} - 1$}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -