.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Math::Random::MT::Auto 3pm" .TH Math::Random::MT::Auto 3pm "2023-02-07" "perl v5.36.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Math::Random::MT::Auto \- Auto\-seeded Mersenne Twister PRNGs .SH "VERSION" .IX Header "VERSION" This documentation refers to Math::Random::MT::Auto version 6.23 .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 5 \& use strict; \& use warnings; \& use Math::Random::MT::Auto qw(rand irand shuffle gaussian), \& \*(Aq/dev/urandom\*(Aq => 256, \& \*(Aqrandom_org\*(Aq; \& \& # Functional interface \& my $die_roll = 1 + int(rand(6)); \& \& my $coin_flip = (irand() & 1) ? \*(Aqheads\*(Aq : \*(Aqtails\*(Aq; \& \& my @deck = shuffle(1 .. 52); \& \& my $rand_IQ = gaussian(15, 100); \& \& # OO interface \& my $prng = Math::Random::MT::Auto\->new(\*(AqSOURCE\*(Aq => \*(Aq/dev/random\*(Aq); \& \& my $angle = $prng\->rand(360); \& \& my $decay_interval = $prng\->exponential(12.4); .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" The Mersenne Twister is a fast pseudorandom number generator (\s-1PRNG\s0) that is capable of providing large volumes (> 10^6004) of \*(L"high quality\*(R" pseudorandom data to applications that may exhaust available \*(L"truly\*(R" random data sources or system-provided PRNGs such as rand. .PP This module provides PRNGs that are based on the Mersenne Twister. There is a functional interface to a single, standalone \s-1PRNG,\s0 and an \s-1OO\s0 interface (based on the inside-out object model as implemented by the Object::InsideOut module) for generating multiple \s-1PRNG\s0 objects. The PRNGs are normally self-seeding, automatically acquiring a (19968\-bit) random seed from user-selectable sources. (\fIManual\fR seeding is optionally available.) .IP "Random Number Deviates" 4 .IX Item "Random Number Deviates" In addition to integer and floating-point uniformly-distributed random number deviates (i.e., \*(L"irand\*(R" and \*(L"rand\*(R"), this module implements the following non-uniform deviates as found in \fINumerical Recipes in C\fR: .RS 4 .RS 4 .IP "\(bu" 4 Gaussian (normal) .IP "\(bu" 4 Exponential .IP "\(bu" 4 Erlang (gamma of integer order) .IP "\(bu" 4 Poisson .IP "\(bu" 4 Binomial .RE .RS 4 .RE .RE .RS 4 .RE .IP "Shuffling" 4 .IX Item "Shuffling" This module also provides a subroutine/method for shuffling data based on the Fisher-Yates shuffling algorithm. .IP "Support for 64\-bit Integers" 4 .IX Item "Support for 64-bit Integers" If Perl has been compiled to support 64\-bit integers (do perl \-V and look for \f(CW\*(C`use64bitint=define\*(C'\fR), then this module will use a 64\-bit\-integer version of the Mersenne Twister, thus providing 64\-bit random integers and 52\-bit random doubles. The size of integers returned by \*(L"irand\*(R", and used by \*(L"get_seed\*(R" and \*(L"set_seed\*(R" will be sized accordingly. .Sp Programmatically, the size of Perl's integers can be determined using the \&\f(CW\*(C`Config\*(C'\fR module: .Sp .Vb 2 \& use Config; \& print("Integers are $Config{\*(Aquvsize\*(Aq} bytes in length\en"); .Ve .PP The code for this module has been optimized for speed. Under Cygwin, it's 2.5 times faster than Math::Random::MT, and under Solaris, it's more than four times faster. (Math::Random::MT fails to build under Windows.) .SH "QUICKSTART" .IX Header "QUICKSTART" To use this module as a drop-in replacement for Perl's built-in rand function, just add the following to the top of your application code: .PP .Vb 3 \& use strict; \& use warnings; \& use Math::Random::MT::Auto \*(Aqrand\*(Aq; .Ve .PP and then just use \*(L"rand\*(R" as you would normally. You don't even need to bother seeding the \s-1PRNG\s0 (i.e., you don't need to call \*(L"srand\*(R"), as that gets done automatically when the module is loaded by Perl. .PP If you need multiple PRNGs, then use the \s-1OO\s0 interface: .PP .Vb 3 \& use strict; \& use warnings; \& use Math::Random::MT::Auto; \& \& my $prng1 = Math::Random::MT::Auto\->new(); \& my $prng2 = Math::Random::MT::Auto\->new(); \& \& my $rand_num = $prng1\->rand(); \& my $rand_int = $prng2\->irand(); .Ve .PP \&\fB\s-1CAUTION\s0\fR: If you want to require this module, see the \&\*(L"Delayed Importation\*(R" section for important information. .SH "MODULE DECLARATION" .IX Header "MODULE DECLARATION" The module must always be declared such that its \f(CW\*(C`\->import()\*(C'\fR method gets called: .PP .Vb 1 \& use Math::Random::MT::Auto; # Correct \& \& #use Math::Random::MT::Auto (); # Does not work because \& # \->import() does not get invoked .Ve .SS "Subroutine Declarations" .IX Subsection "Subroutine Declarations" By default, this module does not automatically export any of its subroutines. If you want to use the standalone \s-1PRNG,\s0 then you should specify the subroutines you want to use when you declare the module: .PP .Vb 3 \& use Math::Random::MT::Auto qw(rand irand shuffle gaussian \& exponential erlang poisson binomial \& srand get_seed set_seed get_state set_state); .Ve .PP Without the above declarations, it is still possible to use the standalone \&\s-1PRNG\s0 by accessing the subroutines using their fully-qualified names. For example: .PP .Vb 1 \& my $rand = Math::Random::MT::Auto::rand(); .Ve .SS "Module Options" .IX Subsection "Module Options" .IP "Seeding Sources" 4 .IX Item "Seeding Sources" Starting the PRNGs with a 19968\-bit random seed (312 64\-bit integers or 624 32\-bit integers) takes advantage of their full range of possible internal vectors states. This module attempts to acquire such seeds using several user-selectable sources. .Sp (I would be interested to hear about other random data sources for possible inclusion in future versions of this module.) .RS 4 .IP "Random Devices" 4 .IX Item "Random Devices" Most OSs offer some sort of device for acquiring random numbers. The most common are \fI/dev/urandom\fR and \fI/dev/random\fR. You can specify the use of these devices for acquiring the seed for the \s-1PRNG\s0 when you declare this module: .Sp .Vb 3 \& use Math::Random::MT::Auto \*(Aq/dev/urandom\*(Aq; \& # or \& my $prng = Math::Random::MT::Auto\->new(\*(AqSOURCE\*(Aq => \*(Aq/dev/random\*(Aq); .Ve .Sp or they can be specified when using \*(L"srand\*(R". .Sp .Vb 3 \& srand(\*(Aq/dev/random\*(Aq); \& # or \& $prng\->srand(\*(Aq/dev/urandom\*(Aq); .Ve .Sp The devices are accessed in \fInon-blocking\fR mode so that if there is insufficient data when they are read, the application will not hang waiting for more. .IP "File of Binary Data" 4 .IX Item "File of Binary Data" Since the above devices are just files as far as Perl is concerned, you can also use random data previously stored in files (in binary format). .Sp .Vb 3 \& srand(\*(AqC:\e\eTemp\e\eRANDOM.DAT\*(Aq); \& # or \& $prng\->srand(\*(Aq/tmp/random.dat\*(Aq); .Ve .IP "Internet Sites" 4 .IX Item "Internet Sites" This module provides support for acquiring seed data from several Internet sites: random.org, HotBits and RandomNumbers.info. An Internet connection and LWP::UserAgent are required to utilize these sources. .Sp .Vb 5 \& use Math::Random::MT::Auto \*(Aqrandom_org\*(Aq; \& # or \& use Math::Random::MT::Auto \*(Aqhotbits\*(Aq; \& # or \& use Math::Random::MT::Auto \*(Aqrn_info\*(Aq; .Ve .Sp If you connect to the Internet through an \s-1HTTP\s0 proxy, then you must set the http_proxy variable in your environment when using these sources. (See \*(L"Proxy attributes\*(R" in LWP::UserAgent.) .Sp The HotBits site will only provide a maximum of 2048 bytes of data per request, and RandomNumbers.info's maximum is 1000. If you want to get the full seed from these sites, then you can specify the source multiple times: .Sp .Vb 2 \& my $prng = Math::Random::MT::Auto\->new(\*(AqSOURCE\*(Aq => [\*(Aqhotbits\*(Aq, \& \*(Aqhotbits\*(Aq]); .Ve .Sp or specify multiple sources: .Sp .Vb 1 \& use Math::Random::MT::Auto qw(rn_info hotbits random_org); .Ve .IP "Windows \s-1XP\s0 Random Data" 4 .IX Item "Windows XP Random Data" Under MSWin32 or Cygwin on Windows \s-1XP,\s0 you can acquire random seed data from the system. .Sp .Vb 1 \& use Math::Random::MT::Auto \*(Aqwin32\*(Aq; .Ve .Sp To utilize this option, you must have the Win32::API module installed. .IP "User-defined Seeding Source" 4 .IX Item "User-defined Seeding Source" A subroutine reference may be specified as a seeding source. When called, it will be passed three arguments: A array reference where seed data is to be added, and the number of integers (64\- or 32\-bit as the case may be) needed. .Sp .Vb 4 \& sub MySeeder \& { \& my $seed = $_[0]; \& my $need = $_[1]; \& \& while ($need\-\-) { \& my $data = ...; # Get seed data from your source \& ... \& push(@{$seed}, $data); \& } \& } \& \& my $prng = Math::Random::MT::Auto\->new(\*(AqSOURCE\*(Aq => \e&MySeeder); .Ve .RE .RS 4 .Sp The default list of seeding sources is determined when the module is loaded. Under MSWin32 or Cygwin on Windows \s-1XP,\s0 \f(CW\*(C`win32\*(C'\fR is added to the list if Win32::API is available. Otherwise, \fI/dev/urandom\fR and then \&\fI/dev/random\fR are checked. The first one found is added to the list. Finally, \f(CW\*(C`random_org\*(C'\fR is added. .Sp For the functional interface to the standalone \s-1PRNG,\s0 these defaults can be overridden by specifying the desired sources when the module is declared, or through the use of the \*(L"srand\*(R" subroutine. Similarly for the \s-1OO\s0 interface, they can be overridden in the \&\->\fBnew()\fR method when the \s-1PRNG\s0 is created, or later using the \*(L"srand\*(R" method. .Sp Optionally, the maximum number of integers (64\- or 32\-bits as the case may be) to be acquired from a particular source may be specified: .Sp .Vb 4 \& # Get at most 1024 bytes from random.org \& # Finish the seed using data from /dev/urandom \& use Math::Random::MT::Auto \*(Aqrandom_org\*(Aq => (1024 / $Config{\*(Aquvsize\*(Aq}), \& \*(Aq/dev/urandom\*(Aq; .Ve .RE .IP "Delayed Seeding" 4 .IX Item "Delayed Seeding" Normally, the standalone \s-1PRNG\s0 is automatically seeded when the module is loaded. This behavior can be modified by supplying the \f(CW\*(C`:!auto\*(C'\fR (or \&\f(CW\*(C`:noauto\*(C'\fR) flag when the module is declared. (The \s-1PRNG\s0 will still be seeded using data such as \fBtime()\fR and \s-1PID\s0 ($$), just in case.) When the \f(CW\*(C`:!auto\*(C'\fR option is used, the \&\*(L"srand\*(R" subroutine should be imported, and then run before calling any of the random number deviates. .Sp .Vb 5 \& use Math::Random::MT::Auto qw(rand srand :!auto); \& ... \& srand(); \& ... \& my $rn = rand(10); .Ve .SS "Delayed Importation" .IX Subsection "Delayed Importation" If you want to delay the importation of this module using require, then you must execute its \f(CW\*(C`\->import()\*(C'\fR method to complete the module's initialization: .PP .Vb 5 \& eval { \& require Math::Random::MT::Auto; \& # You may add options to the import call, if desired. \& Math::Random::MT::Auto\->import(); \& }; .Ve .SH "STANDALONE PRNG OBJECT" .IX Header "STANDALONE PRNG OBJECT" .ie n .IP "my $obj = $MRMA::PRNG;" 4 .el .IP "my \f(CW$obj\fR = \f(CW$MRMA::PRNG\fR;" 4 .IX Item "my $obj = $MRMA::PRNG;" \&\f(CW$MRMA::PRNG\fR is the object that represents the standalone \s-1PRNG.\s0 .SH "OBJECT CREATION" .IX Header "OBJECT CREATION" The \s-1OO\s0 interface for this module allows you to create multiple, independent PRNGs. .PP If your application will only be using the \s-1OO\s0 interface, then declare this module using the :!auto flag to forestall the automatic seeding of the standalone \s-1PRNG:\s0 .PP .Vb 1 \& use Math::Random::MT::Auto \*(Aq:!auto\*(Aq; .Ve .IP "Math::Random::MT::Auto\->new" 4 .IX Item "Math::Random::MT::Auto->new" .Vb 1 \& my $prng = Math::Random::MT::Auto\->new( %options ); .Ve .Sp Creates a new \s-1PRNG.\s0 With no options, the \s-1PRNG\s0 is seeded using the default sources that were determined when the module was loaded, or that were last supplied to the \*(L"srand\*(R" subroutine. .RS 4 .ie n .IP "'\s-1STATE\s0' => $prng_state" 4 .el .IP "'\s-1STATE\s0' => \f(CW$prng_state\fR" 4 .IX Item "'STATE' => $prng_state" Sets the newly created \s-1PRNG\s0 to the specified state. The \s-1PRNG\s0 will then function as a clone of the \s-1RPNG\s0 that the state was obtained from (at the point when then state was obtained). .Sp When the \f(CW\*(C`STATE\*(C'\fR option is used, any other options are just stored (i.e., they are not acted upon). .ie n .IP "'\s-1SEED\s0' => $seed_array_ref" 4 .el .IP "'\s-1SEED\s0' => \f(CW$seed_array_ref\fR" 4 .IX Item "'SEED' => $seed_array_ref" When the \f(CW\*(C`STATE\*(C'\fR option is not used, this option seeds the newly created \&\s-1PRNG\s0 using the supplied seed data. Otherwise, the seed data is just copied to the new object. .IP "'\s-1SOURCE\s0' => 'source'" 4 .IX Item "'SOURCE' => 'source'" .PD 0 .IP "'\s-1SOURCE\s0' => ['source', ...]" 4 .IX Item "'SOURCE' => ['source', ...]" .PD Specifies the seeding source(s) for the \s-1PRNG.\s0 If the \f(CW\*(C`STATE\*(C'\fR and \f(CW\*(C`SEED\*(C'\fR options are not used, then seed data will be immediately fetched using the specified sources, and used to seed the \s-1PRNG.\s0 .Sp The source list is retained for later use by the \*(L"srand\*(R" method. The source list may be replaced by calling the \*(L"srand\*(R" method. .Sp \&'\s-1SOURCES\s0', '\s-1SRC\s0' and '\s-1SRCS\s0' can all be used as synonyms for '\s-1SOURCE\s0'. .RE .RS 4 .Sp The options above are also supported using lowercase and mixed-case names (e.g., 'Seed', 'src', etc.). .RE .ie n .IP "$obj\->new" 4 .el .IP "\f(CW$obj\fR\->new" 4 .IX Item "$obj->new" .Vb 1 \& my $prng2 = $prng1\->new( %options ); .Ve .Sp Creates a new \s-1PRNG\s0 in the same manner as \*(L"Math::Random::MT::Auto\->new\*(R". .ie n .IP "$obj\->clone" 4 .el .IP "\f(CW$obj\fR\->clone" 4 .IX Item "$obj->clone" .Vb 1 \& my $prng2 = $prng1\->clone(); .Ve .Sp Creates a new \s-1PRNG\s0 that is a copy of the referenced \s-1PRNG.\s0 .SH "SUBROUTINES/METHODS" .IX Header "SUBROUTINES/METHODS" When any of the \fIfunctions\fR listed below are invoked as subroutines, they operates with respect to the standalone \s-1PRNG.\s0 For example: .PP .Vb 1 \& my $rand = rand(); .Ve .PP When invoked as methods, they operate on the referenced \s-1PRNG\s0 object: .PP .Vb 1 \& my $rand = $prng\->rand(); .Ve .PP For brevity, only usage examples for the functional interface are given below. .IP "rand" 4 .IX Item "rand" .Vb 2 \& my $rn = rand(); \& my $rn = rand($num); .Ve .Sp Behaves exactly like Perl's built-in rand, returning a number uniformly distributed in [0, \f(CW$num\fR). ($num defaults to 1.) .Sp \&\s-1NOTE:\s0 If you still need to access Perl's built-in rand function, you can do so using \f(CW\*(C`CORE::rand()\*(C'\fR. .IP "irand" 4 .IX Item "irand" .Vb 1 \& my $int = irand(); .Ve .Sp Returns a random integer. For 32\-bit integer Perl, the range is 0 to 2^32\-1 (0xFFFFFFFF) inclusive. For 64\-bit integer Perl, it's 0 to 2^64\-1 inclusive. .Sp This is the fastest way to obtain random numbers using this module. .IP "shuffle" 4 .IX Item "shuffle" .Vb 2 \& my @shuffled = shuffle($data, ...); \& my @shuffled = shuffle(@data); .Ve .Sp Returns an array of the random ordering of the supplied arguments (i.e., shuffled) by using the Fisher-Yates shuffling algorithm. It can also be called to return an array reference: .Sp .Vb 2 \& my $shuffled = shuffle($data, ...); \& my $shuffled = shuffle(@data); .Ve .Sp If called with a single array reference (fastest method), the contents of the array are shuffled in situ: .Sp .Vb 1 \& shuffle(\e@data); .Ve .IP "gaussian" 4 .IX Item "gaussian" .Vb 3 \& my $gn = gaussian(); \& my $gn = gaussian($sd); \& my $gn = gaussian($sd, $mean); .Ve .Sp Returns floating-point random numbers from a Gaussian (normal) distribution (i.e., numbers that fit a bell curve). If called with no arguments, the distribution uses a standard deviation of 1, and a mean of 0. Otherwise, the supplied argument(s) will be used for the standard deviation, and the mean. .IP "exponential" 4 .IX Item "exponential" .Vb 2 \& my $xn = exponential(); \& my $xn = exponential($mean); .Ve .Sp Returns floating-point random numbers from an exponential distribution. If called with no arguments, the distribution uses a mean of 1. Otherwise, the supplied argument will be used for the mean. .Sp An example of an exponential distribution is the time interval between independent Poisson-random events such as radioactive decay. In this case, the mean is the average time between events. This is called the \fImean life\fR for radioactive decay, and its inverse is the decay constant (which represents the expected number of events per unit time). The well known term \&\fIhalf-life\fR is given by \f(CW\*(C`mean * ln(2)\*(C'\fR. .IP "erlang" 4 .IX Item "erlang" .Vb 2 \& my $en = erlang($order); \& my $en = erlang($order, $mean); .Ve .Sp Returns floating-point random numbers from an Erlang distribution of specified order. The order must be a positive integer (> 0). The mean, if not specified, defaults to 1. .Sp The Erlang distribution is the distribution of the sum of \f(CW$order\fR independent identically distributed random variables each having an exponential distribution. (It is a special case of the gamma distribution for which \f(CW$order\fR is a positive integer.) When \f(CW\*(C`$order = 1\*(C'\fR, it is just the exponential distribution. It is named after A. K. Erlang who developed it to predict waiting times in queuing systems. .IP "poisson" 4 .IX Item "poisson" .Vb 2 \& my $pn = poisson($mean); \& my $pn = poisson($rate, $time); .Ve .Sp Returns integer random numbers (>= 0) from a Poisson distribution of specified mean (rate * time = mean). The mean must be a positive value (> 0). .Sp The Poisson distribution predicts the probability of the number of Poisson-random events occurring in a fixed time if these events occur with a known average rate. Examples of events that can be modeled as Poisson distributions include: .RS 4 .RS 4 .IP "\(bu" 4 The number of decays from a radioactive sample within a given time period. .IP "\(bu" 4 The number of cars that pass a certain point on a road within a given time period. .IP "\(bu" 4 The number of phone calls to a call center per minute. .IP "\(bu" 4 The number of road kill found per a given length of road. .RE .RS 4 .RE .RE .RS 4 .RE .IP "binomial" 4 .IX Item "binomial" .Vb 1 \& my $bn = binomial($prob, $trials); .Ve .Sp Returns integer random numbers (>= 0) from a binomial distribution. The probability (\f(CW$prob\fR) must be between 0.0 and 1.0 (inclusive), and the number of trials must be >= 0. .Sp The binomial distribution is the discrete probability distribution of the number of successes in a sequence of \f(CW$trials\fR independent Bernoulli trials (i.e., yes/no experiments), each of which yields success with probability \&\f(CW$prob\fR. .Sp If the number of trials is very large, the binomial distribution may be approximated by a Gaussian distribution. If the average number of successes is small (\f(CW\*(C`$prob * $trials < 1\*(C'\fR), then the binomial distribution can be approximated by a Poisson distribution. .IP "srand" 4 .IX Item "srand" .Vb 2 \& srand(); \& srand(\*(Aqsource\*(Aq, ...); .Ve .Sp This (re)seeds the \s-1PRNG.\s0 It may be called anytime reseeding of the \s-1PRNG\s0 is desired (although this should normally not be needed). .Sp When the :!auto flag is used, the \f(CW\*(C`srand\*(C'\fR subroutine should be called before any other access to the standalone \s-1PRNG.\s0 .Sp When called without arguments, the previously determined/specified seeding source(s) will be used to seed the \s-1PRNG.\s0 .Sp Optionally, seeding sources may be supplied as arguments as when using the \&'\s-1SOURCE\s0' option. (These sources will be saved and used again if \f(CW\*(C`srand\*(C'\fR is subsequently called without arguments). .Sp .Vb 3 \& # Get 250 integers of seed data from Hotbits, \& # and then get the rest from /dev/random \& srand(\*(Aqhotbits\*(Aq => 250, \*(Aq/dev/random\*(Aq); .Ve .Sp If called with integer data (a list of one or more value, or an array of values), or a reference to an array of integers, these data will be passed to \&\*(L"set_seed\*(R" for use in reseeding the \s-1PRNG.\s0 .Sp \&\s-1NOTE:\s0 If you still need to access Perl's built-in srand function, you can do so using \f(CW\*(C`CORE::srand($seed)\*(C'\fR. .IP "get_seed" 4 .IX Item "get_seed" .Vb 3 \& my @seed = get_seed(); \& # or \& my $seed = get_seed(); .Ve .Sp Returns an array or an array reference containing the seed last sent to the \&\s-1PRNG.\s0 .Sp \&\s-1NOTE:\s0 Changing the data in the array will not cause any changes in the \s-1PRNG\s0 (i.e., it will not reseed it). You need to use \*(L"srand\*(R" or \*(L"set_seed\*(R" for that. .IP "set_seed" 4 .IX Item "set_seed" .Vb 3 \& set_seed($seed, ...); \& set_seed(@seed); \& set_seed(\e@seed); .Ve .Sp When called with integer data (a list of one or more value, or an array of values), or a reference to an array of integers, these data will be used to reseed the \s-1PRNG.\s0 .Sp Together with \*(L"get_seed\*(R", \f(CW\*(C`set_seed\*(C'\fR may be useful for setting up identical sequences of random numbers based on the same seed. .Sp It is possible to seed the \s-1PRNG\s0 with more than 19968 bits of data (312 64\-bit integers or 624 32\-bit integers). However, doing so does not make the \s-1PRNG\s0 \&\*(L"more random\*(R" as 19968 bits more than covers all the possible \s-1PRNG\s0 state vectors. .IP "get_state" 4 .IX Item "get_state" .Vb 3 \& my @state = get_state(); \& # or \& my $state = get_state(); .Ve .Sp Returns an array (for list context) or an array reference (for scalar context) containing the current state vector of the \s-1PRNG.\s0 .Sp Note that the state vector is not a full serialization of the \s-1PRNG.\s0 (See \&\*(L"Serialization\*(R" below.) .IP "set_state" 4 .IX Item "set_state" .Vb 3 \& set_state(@state); \& # or \& set_state($state); .Ve .Sp Sets a \s-1PRNG\s0 to the state contained in an array or array reference containing the state previously obtained using \*(L"get_state\*(R". .Sp .Vb 2 \& # Get the current state of the PRNG \& my @state = get_state(); \& \& # Run the PRNG some more \& my $rand1 = irand(); \& \& # Restore the previous state of the PRNG \& set_state(@state); \& \& # Get another random number \& my $rand2 = irand(); \& \& # $rand1 and $rand2 will be equal. .Ve .Sp \&\fB\s-1CAUTION\s0\fR: It should go without saying that you should not modify the values in the state vector obtained from \*(L"get_state\*(R". Doing so and then feeding it to \*(L"set_state\*(R" would be (to say the least) naughty. .SH "INSIDE-OUT OBJECTS" .IX Header "INSIDE-OUT OBJECTS" By using Object::InsideOut, Math::Random::MT::Auto's \s-1PRNG\s0 objects support the following capabilities: .SS "Cloning" .IX Subsection "Cloning" Copies of \s-1PRNG\s0 objects can be created using the \f(CW\*(C`\->clone()\*(C'\fR method. .PP .Vb 1 \& my $prng2 = $prng\->clone(); .Ve .PP See \*(L"Object Cloning\*(R" in Object::InsideOut for more details. .SS "Serialization" .IX Subsection "Serialization" \&\s-1PRNG\s0 objects can be serialized using the \f(CW\*(C`\->dump()\*(C'\fR method. .PP .Vb 3 \& my $array_ref = $prng\->dump(); \& # or \& my $string = $prng\->dump(1); .Ve .PP Serialized object can then be converted back into \s-1PRNG\s0 objects: .PP .Vb 1 \& my $prng2 = Object::InsideOut\->pump($array_ref); .Ve .PP See \*(L"Object Serialization\*(R" in Object::InsideOut for more details. .PP Serialization using Storable is also supported: .PP .Vb 1 \& use Storable qw(freeze thaw); \& \& BEGIN { \& $Math::Random::MT::Auto::storable = 1; \& } \& use Math::Random::MT::Auto ...; \& \& my $prng = Math::Random::MT::Auto\->new(); \& \& my $tmp = $prng\->freeze(); \& my $prng2 = thaw($tmp); .Ve .PP See \*(L"Storable\*(R" in Object::InsideOut for more details. .PP \&\fB\s-1NOTE:\s0\fR Code refs cannot be serialized. Therefore, any \&\*(L"User-defined Seeding Source\*(R" subroutines used in conjunction with \&\*(L"srand\*(R" will be filtered out from the serialized results. .SS "Coercion" .IX Subsection "Coercion" Various forms of object coercion are supported through the overload mechanism. For instance, you can to use a \s-1PRNG\s0 object directly in a string: .PP .Vb 2 \& my $prng = Math::Random::MT::Auto\->new(); \& print("Here\*(Aqs a random integer: $prng\en"); .Ve .PP The \fIstringification\fR of the \s-1PRNG\s0 object is accomplished by calling \&\f(CW\*(C`\->irand()\*(C'\fR on the object, and returning the integer so obtained as the \&\fIcoerced\fR result. .PP A similar overload coercion is performed when the object is used in a numeric context: .PP .Vb 1 \& my $neg_rand = 0 \- $prng; .Ve .PP (See \*(L"\s-1BUGS AND LIMITATIONS\*(R"\s0 regarding numeric overloading on 64\-bit integer Perls prior to 5.10.) .PP In a boolean context, the coercion returns true or false based on whether the call to \f(CW\*(C`\->irand()\*(C'\fR returns an odd or even result: .PP .Vb 5 \& if ($prng) { \& print("Heads \- I win!\en"); \& } else { \& print("Tails \- You lose.\en"); \& } .Ve .PP In an array context, the coercion returns a single integer result: .PP .Vb 1 \& my @rands = @{$prng}; .Ve .PP This may not be all that useful, so you can call the \f(CW\*(C`\->array()\*(C'\fR method directly with a integer argument for the number of random integers you'd like: .PP .Vb 2 \& # Get 20 random integers \& my @rands = @{$prng\->array(20)}; .Ve .PP Finally, a \s-1PRNG\s0 object can be used to produce a code reference that will return random integers each time it is invoked: .PP .Vb 2 \& my $rand = \e&{$prng}; \& my $int = &$rand; .Ve .PP See \*(L"Object Coercion\*(R" in Object::InsideOut for more details. .SS "Thread Support" .IX Subsection "Thread Support" Math::Random::MT::Auto provides thread support to the extent documented in \&\*(L"\s-1THREAD SUPPORT\*(R"\s0 in Object::InsideOut. .PP In a threaded application (i.e., \f(CW\*(C`use threads;\*(C'\fR), the standalone \s-1PRNG\s0 and all the \s-1PRNG\s0 objects from one thread will be copied and made available in a child thread. .PP To enable the sharing of \s-1PRNG\s0 objects between threads, do the following in your application: .PP .Vb 2 \& use threads; \& use threads::shared; \& \& BEGIN { \& $Math::Random::MT::Auto::shared = 1; \& } \& use Math::Random::MT::Auto ...; .Ve .PP \&\fB\s-1NOTE:\s0\fR Code refs cannot be shared between threads. Therefore, you cannot use \*(L"User-defined Seeding Source\*(R" subroutines in conjunction with \&\*(L"srand\*(R" when \f(CW\*(C`use threads::shared;\*(C'\fR is in effect. .PP Depending on your needs, when using threads, but not enabling thread-sharing of \s-1PRNG\s0 objects as per the above, you may want to perform an \f(CW\*(C`srand\*(C'\fR call on the standalone \s-1PRNG\s0 and/or your \s-1PRNG\s0 objects inside the threaded code so that the pseudorandom number sequences generated in each thread differs. .PP .Vb 2 \& use threads; \& use Math::Random:MT::Auto qw(irand srand); \& \& my $prng = Math::Random:MT::Auto\->new(); \& \& sub thr_code \& { \& srand(); \& $prng\->srand(); \& \& .... \& } .Ve .SH "EXAMPLES" .IX Header "EXAMPLES" .IP "Cloning the standalone \s-1PRNG\s0 to an object" 4 .IX Item "Cloning the standalone PRNG to an object" .Vb 1 \& use Math::Random::MT::Auto qw(get_state); \& \& my $prng = Math::Random::MT::Auto\->new(\*(AqSTATE\*(Aq => scalar(get_state())); .Ve .Sp or using the standalone \s-1PRNG\s0 object directly: .Sp .Vb 1 \& my $prng = $Math::Random::MT::Auto::SA_PRNG\->clone(); .Ve .Sp The standalone \s-1PRNG\s0 and the \s-1PRNG\s0 object will now return the same sequence of pseudorandom numbers. .PP Included in this module's distribution are several sample programs (located in the \fIsamples\fR sub-directory) that illustrate the use of the various random number deviates and other features supported by this module. .SH "DIAGNOSTICS" .IX Header "DIAGNOSTICS" .SS "\s-1WARNINGS\s0" .IX Subsection "WARNINGS" Warnings are generated by this module primarily when problems are encountered while trying to obtain random seed data for the PRNGs. This may occur after the module is loaded, after a \s-1PRNG\s0 object is created, or after calling \&\*(L"srand\*(R". .PP These seed warnings are not critical in nature. The \s-1PRNG\s0 will still be seeded (at a minimum using data such as \fBtime()\fR and \s-1PID\s0 ($$)), and can be used safely. .PP The following illustrates how such warnings can be trapped for programmatic handling: .PP .Vb 4 \& my @WARNINGS; \& BEGIN { \& $SIG{_\|_WARN_\|_} = sub { push(@WARNINGS, @_); }; \& } \& \& use Math::Random::MT::Auto; \& \& # Check for standalone PRNG warnings \& if (@WARNINGS) { \& # Handle warnings as desired \& ... \& # Clear warnings \& undef(@WARNINGS); \& } \& \& my $prng = Math::Random::MT::Auto\->new(); \& \& # Check for PRNG object warnings \& if (@WARNINGS) { \& # Handle warnings as desired \& ... \& # Clear warnings \& undef(@WARNINGS); \& } .Ve .IP "\(bu" 4 Failure opening random device '...': ... .Sp The specified device (e.g., /dev/random) could not be opened by the module. Further diagnostic information should be included with this warning message (e.g., device does not exist, permission problem, etc.). .IP "\(bu" 4 Failure setting non-blocking mode on random device '...': ... .Sp The specified device could not be set to \fInon-blocking\fR mode. Further diagnostic information should be included with this warning message (e.g., permission problem, etc.). .IP "\(bu" 4 Failure reading from random device '...': ... .Sp A problem occurred while trying to read from the specified device. Further diagnostic information should be included with this warning message. .IP "\(bu" 4 Random device '...' exhausted .Sp The specified device did not supply the requested number of random numbers for the seed. It could possibly occur if \fI/dev/random\fR is used too frequently. It will occur if the specified device is a file, and it does not have enough data in it. .IP "\(bu" 4 Failure creating user-agent: ... .Sp To utilize the option of acquiring seed data from Internet sources, you need to install the LWP::UserAgent module. .IP "\(bu" 4 Failure contacting \s-1XXX: ...\s0 .IP "\(bu" 4 Failure getting data from \s-1XXX: 500\s0 Can't connect to ... (connect: timeout) .Sp You need to have an Internet connection to utilize \*(L"Internet Sites\*(R" as random seed sources. .Sp If you connect to the Internet through an \s-1HTTP\s0 proxy, then you must set the http_proxy variable in your environment when using the Internet seed sources. (See \*(L"Proxy attributes\*(R" in LWP::UserAgent.) .Sp This module sets a 5 second timeout for Internet connections so that if something goes awry when trying to get seed data from an Internet source, your application will not hang for an inordinate amount of time. .IP "\(bu" 4 You have exceeded your 24\-hour quota for HotBits. .Sp The HotBits site has a quota on the amount of data you can request in a 24\-hour period. (I don't know how big the quota is.) Therefore, this source may fail to provide any data if used too often. .IP "\(bu" 4 Failure acquiring Win \s-1XP\s0 random data: ... .Sp A problem occurred while trying to acquire seed data from the Window \s-1XP\s0 random source. Further diagnostic information should be included with this warning message. .IP "\(bu" 4 Unknown seeding source: ... .Sp The specified seeding source is not recognized by this module. .Sp This error also occurs if you try to use the win32 random data source on something other than MSWin32 or Cygwin on Windows \s-1XP.\s0 .Sp See \*(L"Seeding Sources\*(R" for more information. .IP "\(bu" 4 No seed data obtained from sources \- Setting minimal seed using \s-1PID\s0 and time .Sp This message will occur in combination with some other message(s) above. .Sp If the module cannot acquire any seed data from the specified sources, then data such as \fBtime()\fR and \s-1PID\s0 ($$) will be used to seed the \s-1PRNG.\s0 .IP "\(bu" 4 Partial seed \- only X of Y .Sp This message will occur in combination with some other message(s) above. It informs you of how much seed data was acquired vs. how much was needed. .SS "\s-1ERRORS\s0" .IX Subsection "ERRORS" This module uses \f(CW\*(C`Exception::Class\*(C'\fR for reporting errors. The base error class provided by Object::InsideOut is \f(CW\*(C`OIO\*(C'\fR. Here is an example of the basic manner for trapping and handling errors: .PP .Vb 6 \& my $obj; \& eval { $obj = Math::Random::MT::Auto\->new(); }; \& if (my $e = OIO\->caught()) { \& print(STDERR "Failure creating new PRNG: $e\en"); \& exit(1); \& } .Ve .PP Errors specific to this module have a base class of \f(CW\*(C`MRMA::Args\*(C'\fR, and have the following error messages: .IP "\(bu" 4 Missing argument to 'set_seed' .Sp \&\*(L"set_seed\*(R" must be called with an array ref, or a list of integer seed data. .IP "\(bu" 4 Invalid state vector .Sp \&\*(L"set_state\*(R" was called with an incompatible state vector. For example, a state vector from a 32\-bit integer version of Perl being used with a 64\-bit integer version of Perl. .SH "PERFORMANCE" .IX Header "PERFORMANCE" Under Cygwin, this module is 2.5 times faster than Math::Random::MT, and under Solaris, it's more than four times faster. (Math::Random::MT fails to build under Windows.) The file \fIsamples/timings.pl\fR, included in this module's distribution, can be used to compare timing results. .PP If you connect to the Internet via a phone modem, acquiring seed data may take a second or so. This delay might be apparent when your application is first started, or when creating a new \s-1PRNG\s0 object. This is especially true if you specify multiple \*(L"Internet Sites\*(R" (so as to get the full seed from them) as this results in multiple accesses to the Internet. (If \fI/dev/urandom\fR is available on your machine, then you should definitely consider using the Internet sources only as a secondary source.) .SH "DEPENDENCIES" .IX Header "DEPENDENCIES" .SS "Installation" .IX Subsection "Installation" A 'C' compiler is required for building this module. .PP This module uses the following 'standard' modules for installation: .RS 4 .IP "ExtUtils::MakeMaker" 4 .IX Item "ExtUtils::MakeMaker" .PD 0 .IP "File::Spec" 4 .IX Item "File::Spec" .IP "Test::More" 4 .IX Item "Test::More" .RE .RS 4 .RE .PD .SS "Operation" .IX Subsection "Operation" Requires Perl 5.6.0 or later. .PP This module uses the following 'standard' modules: .RS 4 .IP "Scalar::Util (1.18 or later)" 4 .IX Item "Scalar::Util (1.18 or later)" .PD 0 .IP "Carp" 4 .IX Item "Carp" .IP "Fcntl" 4 .IX Item "Fcntl" .IP "XSLoader" 4 .IX Item "XSLoader" .RE .RS 4 .RE .PD .PP This module uses the following modules available through \s-1CPAN:\s0 .RS 4 .IP "Object::InsideOut (2.06 or later)" 4 .IX Item "Object::InsideOut (2.06 or later)" .PD 0 .IP "Exception::Class (1.22 or later)" 4 .IX Item "Exception::Class (1.22 or later)" .RE .RS 4 .RE .PD .PP To utilize the option of acquiring seed data from Internet sources, you need to install the LWP::UserAgent module. .PP To utilize the option of acquiring seed data from the system's random data source under MSWin32 or Cygwin on Windows \s-1XP,\s0 you need to install the Win32::API module. .SH "BUGS AND LIMITATIONS" .IX Header "BUGS AND LIMITATIONS" This module does not support multiple inheritance. .PP For Perl prior to 5.10, there is a bug in the overload code associated with 64\-bit integers that causes the integer returned by the \f(CW\*(C`\->irand()\*(C'\fR call to be coerced into a floating-point number. The workaround in this case is to call \f(CW\*(C`\->irand()\*(C'\fR directly: .PP .Vb 2 \& # my $neg_rand = 0 \- $prng; # Result is a floating\-point number \& my $neg_rand = 0 \- $prng\->irand(); # Result is an integer number .Ve .PP The transfer of state vector arrays and serialized objects between 32\- and 64\-bit integer versions of Perl is not supported, and will produce an 'Invalid state vector' error. .PP Please submit any bugs, problems, suggestions, patches, etc. to: .SH "SEE ALSO" .IX Header "SEE ALSO" Math::Random::MT::Auto on MetaCPAN: .PP Code repository: .PP Sample code in the \fIexamples\fR directory of this distribution on \s-1CPAN.\s0 .PP The Mersenne Twister is the (current) quintessential pseudorandom number generator. It is fast, and has a period of 2^19937 \- 1. The Mersenne Twister algorithm was developed by Makoto Matsumoto and Takuji Nishimura. It is available in 32\- and 64\-bit integer versions. .PP Wikipedia entries on the Mersenne Twister and pseudorandom number generators, in general: , and .PP random.org generates random numbers from radio frequency noise. .PP HotBits generates random number from a radioactive decay source. .PP RandomNumbers.info generates random number from a quantum optical source. .PP OpenBSD random devices: .PP FreeBSD random devices: .PP Man pages for \fI/dev/random\fR and \fI/dev/urandom\fR on Unix/Linux/Cygwin/Solaris: .PP Windows \s-1XP\s0 random data source: .PP Fisher-Yates Shuffling Algorithm: , and \fBshuffle()\fR in List::Util .PP Non-uniform random number deviates in \fINumerical Recipes in C\fR, Chapters 7.2 and 7.3: .PP Inside-out Object Model: Object::InsideOut .PP Math::Random::MT::Auto::Range \- Subclass of Math::Random::MT::Auto that creates range-valued PRNGs .PP LWP::UserAgent .PP Math::Random::MT .PP Net::Random .SH "AUTHOR" .IX Header "AUTHOR" Jerry D. Hedden, .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" A C\-Program for \s-1MT19937\s0 (32\- and 64\-bit versions), with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto, and including Shawn Cokus's optimizations. .PP .Vb 4 \& Copyright (C) 1997 \- 2004, Makoto Matsumoto and Takuji Nishimura, \& All rights reserved. \& Copyright (C) 2005, Mutsuo Saito, All rights reserved. \& Copyright 2005 \- 2009 Jerry D. Hedden .Ve .PP Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: .PP 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. .PP 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. .PP 3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission. .PP \&\s-1THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \&\*(L"AS IS\*(R" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\s0 \s-1IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\s0 (\s-1INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES\s0; \s-1LOSS OF USE, DATA, OR PROFITS\s0; \s-1OR BUSINESS INTERRUPTION\s0) \s-1HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\s0 (\s-1INCLUDING NEGLIGENCE OR OTHERWISE\s0) \s-1ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\s0 .PP .Vb 3 \& Any feedback is very welcome. \& m\-mat AT math DOT sci DOT hiroshima\-u DOT ac DOT jp \& http://www.math.sci.hiroshima\-u.ac.jp/~m\-mat/MT/emt.html .Ve