📄 rng.texi
字号:
@cindex random number generatorsThe library provides a large collection of random number generatorswhich can be accessed through a uniform interface. Environmentvariables allow you to select different generators and seeds at runtime,so that you can easily switch between generators without needing torecompile your program. Each instance of a generator keeps track of itsown state, allowing the generators to be used in multi-threadedprograms. Additional functions are available for transforming uniformrandom numbers into samples from continuous or discrete probabilitydistributions 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 numbersIn 1988, Park and Miller wrote a paper entitled ``Random numbergenerators: 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 thesystem-supplied random number generator on your computer, but you shouldbe aware that as computers get faster, requirements on random numbergenerators increase. Nowadays, a simulation that calls a random numbergenerator millions of times can often finish before you can make it downthe hall to the coffee machine and back.A very nice review of random number generators was written by PierreL'Ecuyer, as Chapter 4 of the book: Handbook on Simulation, Jerry Banks,ed. (Wiley, 1997). The chapter is available in postscript fromL'Ecuyer's ftp site (see references). Knuth's volume on SeminumericalAlgorithms (originally published in 1968) devotes 170 pages to randomnumber 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 readingright now, run to the nearest bookstore, and buy it.A good random number generator will satisfy both theoretical andstatistical properties. Theoretical properties are often hard to obtain(they require real math!), but one prefers a random number generatorwith a long period, low serial correlation, and a tendency @emph{not} to``fall mainly on the planes.'' Statistical tests are performed withnumerical simulations. Generally, a random number generator is used toestimate some quantity for which the theory of probability provides anexact answer. Comparison to this exact answer provides a measure of``randomness''.@node The Random Number Generator Interface@section The Random Number Generator InterfaceIt is important to remember that a random number generator is not a``real'' function like sine or cosine. Unlike real functions, successivecalls to a random number generator yield different return values. Ofcourse that is just what you want for a random number generator, but toachieve this effect, the generator must keep track of some kind of``state'' variable. Sometimes this state is just an integer (sometimesjust the value of the previously generated random number), but often itis more complicated than that and may involve a whole array of numbers,possibly with some indices thrown in. To use the random numbergenerators, you do not need to know the details of what comprises thestate, 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 ofgenerator and @code{gsl_rng} which describes an instance of a generatorcreated 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-createdinstance of a random number generator of type @var{T}.For example, the following code creates an instance of the Tausworthegenerator,@examplegsl_rng * r = gsl_rng_alloc (gsl_rng_taus);@end exampleIf there is insufficient memory to create the generator then thefunction returns a null pointer and the error handler is invoked with anerror 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 changedeither directly or by using the environment variable @code{GSL_RNG_SEED}(@pxref{Random number environment variables}).The details of the available generator types aredescribed 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. Ifthe generator is seeded with the same value of @var{s} on two differentruns, the same stream of random numbers will be generated by successivecalls to the routines below. If different values of @var{s} aresupplied, then the generated streams of random numbers should becompletely different. If the seed @var{s} is zero then the standard seedfrom the original implementation is used instead. For example, theoriginal Fortran source code for the @code{ranlux} generator used a seedof 314159265, and so choosing @var{s} equal to zero reproduces this whenusing @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 generatorThe following functions return uniformly distributed random numbers,either as integers or double precision floating point numbers. To obtainnon-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}. Theminimum and maximum values depend on the algorithm used, but allintegers in the range [@var{min},@var{max}] are equally likely. Thevalues of @var{min} and @var{max} can determined using the auxiliaryfunctions @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 uniformlydistributed 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 doubleprecision. Some generators compute this ratio internally so that theycan 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 numberuniformly 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 usethis 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, regardlessof the generator used. An offset correction is applied so that zero isalways returned with the correct probability, for any minimum value ofthe underlying generator.If @var{n} is larger than the range of the generator then the functioncalls the error handler with an error code of @code{GSL_EINVAL} andreturns zero.@end deftypefn@node Auxiliary random number generator functions@section Auxiliary random number generator functionsThe following functions provide information about an existinggenerator. You should use them in preference to hard-coding the generatorparameters 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,@exampleprintf ("r is a '%s' generator\n", gsl_rng_name (r));@end example@noindentwould 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 withalgorithms that cannot return zero, and for these generators the minimumvalue 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} andits size. You can use this information to access the state directly. Forexample, the following code will write the state of a generator to astream,@examplevoid * 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 availablegenerator types, terminated by a null pointer. The function should becalled once at the start of the program, if needed. The following codefragment shows how to iterate over the array of generator types to printthe names of the available algorithms,@exampleconst 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 variablesThe library allows you to choose a default generator and seed from theenvironment variables @code{GSL_RNG_TYPE} and @code{GSL_RNG_SEED} andthe function @code{gsl_rng_env_setup}. This makes it easy try outdifferent 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 correspondinglibrary variables @code{gsl_rng_default} and@code{gsl_rng_default_seed}. These global variables are defined asfollows,@exampleextern const gsl_rng_type *gsl_rng_defaultextern unsigned long int gsl_rng_default_seed@end exampleThe environment variable @code{GSL_RNG_TYPE} should be the name of agenerator, such as @code{taus} or @code{mt19937}. The environmentvariable @code{GSL_RNG_SEED} should contain the desired seed value. Itis 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@noindentHere is a short program which shows how to create a globalgenerator using the environment variables @code{GSL_RNG_TYPE} and@code{GSL_RNG_SEED},@example@verbatiminclude examples/rng.c@end example@noindentRunning the program without any environment variables uses the initialdefaults, an @code{mt19937} generator with a seed of 0,@examplebash$ ./a.out @verbatiminclude examples/rng.out@end example@noindentBy setting the two variables on the command line we canchange the default generator and the seed,@examplebash$ GSL_RNG_TYPE="taus" GSL_RNG_SEED=123 ./a.out GSL_RNG_TYPE=tausGSL_RNG_SEED=123generator type: tausseed = 123first value = 2720986350@end example@node Copying random number generator state@section Copying random number generator stateThe above methods ignore the random number `state' which changes fromcall to call. It is often useful to be able to save and restore thestate. To permit these practices, a few somewhat more advancedfunctions 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 thepre-existing generator @var{dest}, making @var{dest} into an exact copyof @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 anexact copy of the generator @var{r}.@end deftypefn@node Reading and writing random number generator state @section Reading and writing random number generator stateThe library provides functions for reading and writing the randomnumber 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 numbergenerator @var{r} to the stream @var{stream} in binary format. Thereturn value is 0 for success and @code{GSL_EFAILED} if there was aproblem writing to the file. Since the data is written in the nativebinary 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 numbergenerator @var{r} from the open stream @var{stream} in binary format.The random number generator @var{r} must be preinitialized with thecorrect random number generator type since type information is notsaved. The return value is 0 for success and @code{GSL_EFAILED} ifthere was a problem reading from the file. The data is assumed tohave been written in the native binary format on the samearchitecture.@end deftypefun@node Random number generator algorithms@section Random number generator algorithmsThe functions described above make no reference to the actual algorithmused. This is deliberate so that you can switch algorithms withouthaving to change any of your application source code. The libraryprovides a large number of generators of different types, includingsimulation quality generators, generators provided for compatibilitywith other libraries and historical generators from the past.The following generators are recommended for use in simulation. Theyhave extremely long periods, low correlation and pass most statisticaltests.@deffn {Generator} gsl_rng_mt19937@cindex MT19937 random number generatorThe MT19937 generator of Makoto Matsumoto and Takuji Nishimura is avariant of the twisted generalized feedback shift-register algorithm,and is known as the "Mersenne Twister" generator. It has a Mersenneprime period of @comment@c{$2^{19937} - 1$}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -