1Math::Random::MT::Auto(U3s)er Contributed Perl DocumentatMiaotnh::Random::MT::Auto(3)
2
3
4

NAME

6       Math::Random::MT::Auto - Auto-seeded Mersenne Twister PRNGs
7

VERSION

9       This documentation refers to Math::Random::MT::Auto version 6.23
10

SYNOPSIS

12        use strict;
13        use warnings;
14        use Math::Random::MT::Auto qw(rand irand shuffle gaussian),
15                                   '/dev/urandom' => 256,
16                                   'random_org';
17
18        # Functional interface
19        my $die_roll = 1 + int(rand(6));
20
21        my $coin_flip = (irand() & 1) ? 'heads' : 'tails';
22
23        my @deck = shuffle(1 .. 52);
24
25        my $rand_IQ = gaussian(15, 100);
26
27        # OO interface
28        my $prng = Math::Random::MT::Auto->new('SOURCE' => '/dev/random');
29
30        my $angle = $prng->rand(360);
31
32        my $decay_interval = $prng->exponential(12.4);
33

DESCRIPTION

35       The Mersenne Twister is a fast pseudorandom number generator (PRNG)
36       that is capable of providing large volumes (> 10^6004) of "high
37       quality" pseudorandom data to applications that may exhaust available
38       "truly" random data sources or system-provided PRNGs such as rand.
39
40       This module provides PRNGs that are based on the Mersenne Twister.
41       There is a functional interface to a single, standalone PRNG, and an OO
42       interface (based on the inside-out object model as implemented by the
43       Object::InsideOut module) for generating multiple PRNG objects.  The
44       PRNGs are normally self-seeding, automatically acquiring a (19968-bit)
45       random seed from user-selectable sources.  (Manual seeding is
46       optionally available.)
47
48       Random Number Deviates
49           In addition to integer and floating-point uniformly-distributed
50           random number deviates (i.e., "irand" and "rand"), this module
51           implements the following non-uniform deviates as found in Numerical
52           Recipes in C:
53
54               •   Gaussian (normal)
55
56               •   Exponential
57
58               •   Erlang (gamma of integer order)
59
60               •   Poisson
61
62               •   Binomial
63
64       Shuffling
65           This module also provides a subroutine/method for shuffling data
66           based on the Fisher-Yates shuffling algorithm.
67
68       Support for 64-bit Integers
69           If Perl has been compiled to support 64-bit integers (do perl -V
70           and look for "use64bitint=define"), then this module will use a
71           64-bit-integer version of the Mersenne Twister, thus providing
72           64-bit random integers and 52-bit random doubles.  The size of
73           integers returned by "irand", and used by "get_seed" and "set_seed"
74           will be sized accordingly.
75
76           Programmatically, the size of Perl's integers can be determined
77           using the "Config" module:
78
79            use Config;
80            print("Integers are $Config{'uvsize'} bytes in length\n");
81
82       The code for this module has been optimized for speed.  Under Cygwin,
83       it's 2.5 times faster than Math::Random::MT, and under Solaris, it's
84       more than four times faster.  (Math::Random::MT fails to build under
85       Windows.)
86

QUICKSTART

88       To use this module as a drop-in replacement for Perl's built-in rand
89       function, just add the following to the top of your application code:
90
91        use strict;
92        use warnings;
93        use Math::Random::MT::Auto 'rand';
94
95       and then just use "rand" as you would normally.  You don't even need to
96       bother seeding the PRNG (i.e., you don't need to call "srand"), as that
97       gets done automatically when the module is loaded by Perl.
98
99       If you need multiple PRNGs, then use the OO interface:
100
101        use strict;
102        use warnings;
103        use Math::Random::MT::Auto;
104
105        my $prng1 = Math::Random::MT::Auto->new();
106        my $prng2 = Math::Random::MT::Auto->new();
107
108        my $rand_num = $prng1->rand();
109        my $rand_int = $prng2->irand();
110
111       CAUTION: If you want to require this module, see the "Delayed
112       Importation" section for important information.
113

MODULE DECLARATION

115       The module must always be declared such that its "->import()" method
116       gets called:
117
118        use Math::Random::MT::Auto;            # Correct
119
120        #use Math::Random::MT::Auto ();        # Does not work because
121                                               #   ->import() does not get invoked
122
123   Subroutine Declarations
124       By default, this module does not automatically export any of its
125       subroutines.  If you want to use the standalone PRNG, then you should
126       specify the subroutines you want to use when you declare the module:
127
128        use Math::Random::MT::Auto qw(rand irand shuffle gaussian
129                                      exponential erlang poisson binomial
130                                      srand get_seed set_seed get_state set_state);
131
132       Without the above declarations, it is still possible to use the
133       standalone PRNG by accessing the subroutines using their fully-
134       qualified names.  For example:
135
136        my $rand = Math::Random::MT::Auto::rand();
137
138   Module Options
139       Seeding Sources
140           Starting the PRNGs with a 19968-bit random seed (312 64-bit
141           integers or 624 32-bit integers) takes advantage of their full
142           range of possible internal vectors states.  This module attempts to
143           acquire such seeds using several user-selectable sources.
144
145           (I would be interested to hear about other random data sources for
146           possible inclusion in future versions of this module.)
147
148           Random Devices
149               Most OSs offer some sort of device for acquiring random
150               numbers.  The most common are /dev/urandom and /dev/random.
151               You can specify the use of these devices for acquiring the seed
152               for the PRNG when you declare this module:
153
154                use Math::Random::MT::Auto '/dev/urandom';
155                  # or
156                my $prng = Math::Random::MT::Auto->new('SOURCE' => '/dev/random');
157
158               or they can be specified when using "srand".
159
160                srand('/dev/random');
161                  # or
162                $prng->srand('/dev/urandom');
163
164               The devices are accessed in non-blocking mode so that if there
165               is insufficient data when they are read, the application will
166               not hang waiting for more.
167
168           File of Binary Data
169               Since the above devices are just files as far as Perl is
170               concerned, you can also use random data previously stored in
171               files (in binary format).
172
173                srand('C:\\Temp\\RANDOM.DAT');
174                  # or
175                $prng->srand('/tmp/random.dat');
176
177           Internet Sites
178               This module provides support for acquiring seed data from
179               several Internet sites:  random.org, HotBits and
180               RandomNumbers.info.  An Internet connection and LWP::UserAgent
181               are required to utilize these sources.
182
183                use Math::Random::MT::Auto 'random_org';
184                  # or
185                use Math::Random::MT::Auto 'hotbits';
186                  # or
187                use Math::Random::MT::Auto 'rn_info';
188
189               If you connect to the Internet through an HTTP proxy, then you
190               must set the http_proxy variable in your environment when using
191               these sources.  (See "Proxy attributes" in LWP::UserAgent.)
192
193               The HotBits site will only provide a maximum of 2048 bytes of
194               data per request, and RandomNumbers.info's maximum is 1000.  If
195               you want to get the full seed from these sites, then you can
196               specify the source multiple times:
197
198                my $prng = Math::Random::MT::Auto->new('SOURCE' => ['hotbits',
199                                                                    'hotbits']);
200
201               or specify multiple sources:
202
203                use Math::Random::MT::Auto qw(rn_info hotbits random_org);
204
205           Windows XP Random Data
206               Under MSWin32 or Cygwin on Windows XP, you can acquire random
207               seed data from the system.
208
209                use Math::Random::MT::Auto 'win32';
210
211               To utilize this option, you must have the Win32::API module
212               installed.
213
214           User-defined Seeding Source
215               A subroutine reference may be specified as a seeding source.
216               When called, it will be passed three arguments:  A array
217               reference where seed data is to be added, and the number of
218               integers (64- or 32-bit as the case may be) needed.
219
220                sub MySeeder
221                {
222                    my $seed = $_[0];
223                    my $need = $_[1];
224
225                    while ($need--) {
226                        my $data = ...;      # Get seed data from your source
227                        ...
228                        push(@{$seed}, $data);
229                    }
230                }
231
232                my $prng = Math::Random::MT::Auto->new('SOURCE' => \&MySeeder);
233
234           The default list of seeding sources is determined when the module
235           is loaded.  Under MSWin32 or Cygwin on Windows XP, "win32" is added
236           to the list if Win32::API is available.  Otherwise, /dev/urandom
237           and then /dev/random are checked.  The first one found is added to
238           the list.  Finally, "random_org" is added.
239
240           For the functional interface to the standalone PRNG, these defaults
241           can be overridden by specifying the desired sources when the module
242           is declared, or through the use of the "srand" subroutine.
243           Similarly for the OO interface, they can be overridden in the
244           ->new() method when the PRNG is created, or later using the "srand"
245           method.
246
247           Optionally, the maximum number of integers (64- or 32-bits as the
248           case may be) to be acquired from a particular source may be
249           specified:
250
251            # Get at most 1024 bytes from random.org
252            # Finish the seed using data from /dev/urandom
253            use Math::Random::MT::Auto 'random_org' => (1024 / $Config{'uvsize'}),
254                                       '/dev/urandom';
255
256       Delayed Seeding
257           Normally, the standalone PRNG is automatically seeded when the
258           module is loaded.  This behavior can be modified by supplying the
259           ":!auto" (or ":noauto") flag when the module is declared.  (The
260           PRNG will still be seeded using data such as time() and PID ($$),
261           just in case.)  When the ":!auto" option is used, the "srand"
262           subroutine should be imported, and then run before calling any of
263           the random number deviates.
264
265            use Math::Random::MT::Auto qw(rand srand :!auto);
266              ...
267            srand();
268              ...
269            my $rn = rand(10);
270
271   Delayed Importation
272       If you want to delay the importation of this module using require, then
273       you must execute its "->import()" method to complete the module's
274       initialization:
275
276        eval {
277            require Math::Random::MT::Auto;
278            # You may add options to the import call, if desired.
279            Math::Random::MT::Auto->import();
280        };
281

STANDALONE PRNG OBJECT

283       my $obj = $MRMA::PRNG;
284           $MRMA::PRNG is the object that represents the standalone PRNG.
285

OBJECT CREATION

287       The OO interface for this module allows you to create multiple,
288       independent PRNGs.
289
290       If your application will only be using the OO interface, then declare
291       this module using the :!auto flag to forestall the automatic seeding of
292       the standalone PRNG:
293
294        use Math::Random::MT::Auto ':!auto';
295
296       Math::Random::MT::Auto->new
297            my $prng = Math::Random::MT::Auto->new( %options );
298
299           Creates a new PRNG.  With no options, the PRNG is seeded using the
300           default sources that were determined when the module was loaded, or
301           that were last supplied to the "srand" subroutine.
302
303           'STATE' => $prng_state
304               Sets the newly created PRNG to the specified state.  The PRNG
305               will then function as a clone of the RPNG that the state was
306               obtained from (at the point when then state was obtained).
307
308               When the "STATE" option is used, any other options are just
309               stored (i.e., they are not acted upon).
310
311           'SEED' => $seed_array_ref
312               When the "STATE" option is not used, this option seeds the
313               newly created PRNG using the supplied seed data.  Otherwise,
314               the seed data is just copied to the new object.
315
316           'SOURCE' => 'source'
317           'SOURCE' => ['source', ...]
318               Specifies the seeding source(s) for the PRNG.  If the "STATE"
319               and "SEED" options are not used, then seed data will be
320               immediately fetched using the specified sources, and used to
321               seed the PRNG.
322
323               The source list is retained for later use by the "srand"
324               method.  The source list may be replaced by calling the "srand"
325               method.
326
327               'SOURCES', 'SRC' and 'SRCS' can all be used as synonyms for
328               'SOURCE'.
329
330           The options above are also supported using lowercase and mixed-case
331           names (e.g., 'Seed', 'src', etc.).
332
333       $obj->new
334            my $prng2 = $prng1->new( %options );
335
336           Creates a new PRNG in the same manner as
337           "Math::Random::MT::Auto->new".
338
339       $obj->clone
340            my $prng2 = $prng1->clone();
341
342           Creates a new PRNG that is a copy of the referenced PRNG.
343

SUBROUTINES/METHODS

345       When any of the functions listed below are invoked as subroutines, they
346       operates with respect to the standalone PRNG.  For example:
347
348        my $rand = rand();
349
350       When invoked as methods, they operate on the referenced PRNG object:
351
352        my $rand = $prng->rand();
353
354       For brevity, only usage examples for the functional interface are given
355       below.
356
357       rand
358            my $rn = rand();
359            my $rn = rand($num);
360
361           Behaves exactly like Perl's built-in rand, returning a number
362           uniformly distributed in [0, $num).  ($num defaults to 1.)
363
364           NOTE: If you still need to access Perl's built-in rand function,
365           you can do so using "CORE::rand()".
366
367       irand
368            my $int = irand();
369
370           Returns a random integer.  For 32-bit integer Perl, the range is 0
371           to 2^32-1 (0xFFFFFFFF) inclusive.  For 64-bit integer Perl, it's 0
372           to 2^64-1 inclusive.
373
374           This is the fastest way to obtain random numbers using this module.
375
376       shuffle
377            my @shuffled = shuffle($data, ...);
378            my @shuffled = shuffle(@data);
379
380           Returns an array of the random ordering of the supplied arguments
381           (i.e., shuffled) by using the Fisher-Yates shuffling algorithm.  It
382           can also be called to return an array reference:
383
384            my $shuffled = shuffle($data, ...);
385            my $shuffled = shuffle(@data);
386
387           If called with a single array reference (fastest method), the
388           contents of the array are shuffled in situ:
389
390            shuffle(\@data);
391
392       gaussian
393            my $gn = gaussian();
394            my $gn = gaussian($sd);
395            my $gn = gaussian($sd, $mean);
396
397           Returns floating-point random numbers from a Gaussian (normal)
398           distribution (i.e., numbers that fit a bell curve).  If called with
399           no arguments, the distribution uses a standard deviation of 1, and
400           a mean of 0.  Otherwise, the supplied argument(s) will be used for
401           the standard deviation, and the mean.
402
403       exponential
404            my $xn = exponential();
405            my $xn = exponential($mean);
406
407           Returns floating-point random numbers from an exponential
408           distribution.  If called with no arguments, the distribution uses a
409           mean of 1.  Otherwise, the supplied argument will be used for the
410           mean.
411
412           An example of an exponential distribution is the time interval
413           between independent Poisson-random events such as radioactive
414           decay.  In this case, the mean is the average time between events.
415           This is called the mean life for radioactive decay, and its inverse
416           is the decay constant (which represents the expected number of
417           events per unit time).  The well known term half-life is given by
418           "mean * ln(2)".
419
420       erlang
421            my $en = erlang($order);
422            my $en = erlang($order, $mean);
423
424           Returns floating-point random numbers from an Erlang distribution
425           of specified order.  The order must be a positive integer (> 0).
426           The mean, if not specified, defaults to 1.
427
428           The Erlang distribution is the distribution of the sum of $order
429           independent identically distributed random variables each having an
430           exponential distribution.  (It is a special case of the gamma
431           distribution for which $order is a positive integer.)  When "$order
432           = 1", it is just the exponential distribution.  It is named after
433           A. K. Erlang who developed it to predict waiting times in queuing
434           systems.
435
436       poisson
437            my $pn = poisson($mean);
438            my $pn = poisson($rate, $time);
439
440           Returns integer random numbers (>= 0) from a Poisson distribution
441           of specified mean (rate * time = mean).  The mean must be a
442           positive value (> 0).
443
444           The Poisson distribution predicts the probability of the number of
445           Poisson-random events occurring in a fixed time if these events
446           occur with a known average rate.  Examples of events that can be
447           modeled as Poisson distributions include:
448
449               •   The number of decays from a radioactive sample within a
450                   given time period.
451
452               •   The number of cars that pass a certain point on a road
453                   within a given time period.
454
455               •   The number of phone calls to a call center per minute.
456
457               •   The number of road kill found per a given length of road.
458
459       binomial
460            my $bn = binomial($prob, $trials);
461
462           Returns integer random numbers (>= 0) from a binomial distribution.
463           The probability ($prob) must be between 0.0 and 1.0 (inclusive),
464           and the number of trials must be >= 0.
465
466           The binomial distribution is the discrete probability distribution
467           of the number of successes in a sequence of $trials independent
468           Bernoulli trials (i.e., yes/no experiments), each of which yields
469           success with probability $prob.
470
471           If the number of trials is very large, the binomial distribution
472           may be approximated by a Gaussian distribution. If the average
473           number of successes is small ("$prob * $trials < 1"), then the
474           binomial distribution can be approximated by a Poisson
475           distribution.
476
477       srand
478            srand();
479            srand('source', ...);
480
481           This (re)seeds the PRNG.  It may be called anytime reseeding of the
482           PRNG is desired (although this should normally not be needed).
483
484           When the :!auto flag is used, the "srand" subroutine should be
485           called before any other access to the standalone PRNG.
486
487           When called without arguments, the previously determined/specified
488           seeding source(s) will be used to seed the PRNG.
489
490           Optionally, seeding sources may be supplied as arguments as when
491           using the 'SOURCE' option.  (These sources will be saved and used
492           again if "srand" is subsequently called without arguments).
493
494            # Get 250 integers of seed data from Hotbits,
495            #  and then get the rest from /dev/random
496            srand('hotbits' => 250, '/dev/random');
497
498           If called with integer data (a list of one or more value, or an
499           array of values), or a reference to an array of integers, these
500           data will be passed to "set_seed" for use in reseeding the PRNG.
501
502           NOTE: If you still need to access Perl's built-in srand function,
503           you can do so using "CORE::srand($seed)".
504
505       get_seed
506            my @seed = get_seed();
507              # or
508            my $seed = get_seed();
509
510           Returns an array or an array reference containing the seed last
511           sent to the PRNG.
512
513           NOTE: Changing the data in the array will not cause any changes in
514           the PRNG (i.e., it will not reseed it).  You need to use "srand" or
515           "set_seed" for that.
516
517       set_seed
518            set_seed($seed, ...);
519            set_seed(@seed);
520            set_seed(\@seed);
521
522           When called with integer data (a list of one or more value, or an
523           array of values), or a reference to an array of integers, these
524           data will be used to reseed the PRNG.
525
526           Together with "get_seed", "set_seed" may be useful for setting up
527           identical sequences of random numbers based on the same seed.
528
529           It is possible to seed the PRNG with more than 19968 bits of data
530           (312 64-bit integers or 624 32-bit integers).  However, doing so
531           does not make the PRNG "more random" as 19968 bits more than covers
532           all the possible PRNG state vectors.
533
534       get_state
535            my @state = get_state();
536              # or
537            my $state = get_state();
538
539           Returns an array (for list context) or an array reference (for
540           scalar context) containing the current state vector of the PRNG.
541
542           Note that the state vector is not a full serialization of the PRNG.
543           (See "Serialization" below.)
544
545       set_state
546            set_state(@state);
547              # or
548            set_state($state);
549
550           Sets a PRNG to the state contained in an array or array reference
551           containing the state previously obtained using "get_state".
552
553            # Get the current state of the PRNG
554            my @state = get_state();
555
556            # Run the PRNG some more
557            my $rand1 = irand();
558
559            # Restore the previous state of the PRNG
560            set_state(@state);
561
562            # Get another random number
563            my $rand2 = irand();
564
565            # $rand1 and $rand2 will be equal.
566
567           CAUTION:  It should go without saying that you should not modify
568           the values in the state vector obtained from "get_state".  Doing so
569           and then feeding it to "set_state" would be (to say the least)
570           naughty.
571

INSIDE-OUT OBJECTS

573       By using Object::InsideOut, Math::Random::MT::Auto's PRNG objects
574       support the following capabilities:
575
576   Cloning
577       Copies of PRNG objects can be created using the "->clone()" method.
578
579        my $prng2 = $prng->clone();
580
581       See "Object Cloning" in Object::InsideOut for more details.
582
583   Serialization
584       PRNG objects can be serialized using the "->dump()" method.
585
586        my $array_ref = $prng->dump();
587          # or
588        my $string = $prng->dump(1);
589
590       Serialized object can then be converted back into PRNG objects:
591
592        my $prng2 = Object::InsideOut->pump($array_ref);
593
594       See "Object Serialization" in Object::InsideOut for more details.
595
596       Serialization using Storable is also supported:
597
598        use Storable qw(freeze thaw);
599
600        BEGIN {
601            $Math::Random::MT::Auto::storable = 1;
602        }
603        use Math::Random::MT::Auto ...;
604
605        my $prng = Math::Random::MT::Auto->new();
606
607        my $tmp = $prng->freeze();
608        my $prng2 = thaw($tmp);
609
610       See "Storable" in Object::InsideOut for more details.
611
612       NOTE: Code refs cannot be serialized. Therefore, any "User-defined
613       Seeding Source" subroutines used in conjunction with "srand" will be
614       filtered out from the serialized results.
615
616   Coercion
617       Various forms of object coercion are supported through the overload
618       mechanism.  For instance, you can to use a PRNG object directly in a
619       string:
620
621        my $prng = Math::Random::MT::Auto->new();
622        print("Here's a random integer: $prng\n");
623
624       The stringification of the PRNG object is accomplished by calling
625       "->irand()" on the object, and returning the integer so obtained as the
626       coerced result.
627
628       A similar overload coercion is performed when the object is used in a
629       numeric context:
630
631        my $neg_rand = 0 - $prng;
632
633       (See "BUGS AND LIMITATIONS" regarding numeric overloading on 64-bit
634       integer Perls prior to 5.10.)
635
636       In a boolean context, the coercion returns true or false based on
637       whether the call to "->irand()" returns an odd or even result:
638
639        if ($prng) {
640            print("Heads - I win!\n");
641        } else {
642            print("Tails - You lose.\n");
643        }
644
645       In an array context, the coercion returns a single integer result:
646
647        my @rands = @{$prng};
648
649       This may not be all that useful, so you can call the "->array()" method
650       directly with a integer argument for the number of random integers
651       you'd like:
652
653        # Get 20 random integers
654        my @rands = @{$prng->array(20)};
655
656       Finally, a PRNG object can be used to produce a code reference that
657       will return random integers each time it is invoked:
658
659        my $rand = \&{$prng};
660        my $int = &$rand;
661
662       See "Object Coercion" in Object::InsideOut for more details.
663
664   Thread Support
665       Math::Random::MT::Auto provides thread support to the extent documented
666       in "THREAD SUPPORT" in Object::InsideOut.
667
668       In a threaded application (i.e., "use threads;"), the standalone PRNG
669       and all the PRNG objects from one thread will be copied and made
670       available in a child thread.
671
672       To enable the sharing of PRNG objects between threads, do the following
673       in your application:
674
675        use threads;
676        use threads::shared;
677
678        BEGIN {
679            $Math::Random::MT::Auto::shared = 1;
680        }
681        use Math::Random::MT::Auto ...;
682
683       NOTE: Code refs cannot be shared between threads. Therefore, you cannot
684       use "User-defined Seeding Source" subroutines in conjunction with
685       "srand" when "use threads::shared;" is in effect.
686
687       Depending on your needs, when using threads, but not enabling thread-
688       sharing of PRNG objects as per the above, you may want to perform an
689       "srand" call on the standalone PRNG and/or your PRNG objects inside the
690       threaded code so that the pseudorandom number sequences generated in
691       each thread differs.
692
693        use threads;
694        use Math::Random:MT::Auto qw(irand srand);
695
696        my $prng = Math::Random:MT::Auto->new();
697
698        sub thr_code
699        {
700            srand();
701            $prng->srand();
702
703            ....
704        }
705

EXAMPLES

707       Cloning the standalone PRNG to an object
708            use Math::Random::MT::Auto qw(get_state);
709
710            my $prng = Math::Random::MT::Auto->new('STATE' => scalar(get_state()));
711
712           or using the standalone PRNG object directly:
713
714            my $prng = $Math::Random::MT::Auto::SA_PRNG->clone();
715
716           The standalone PRNG and the PRNG object will now return the same
717           sequence of pseudorandom numbers.
718
719       Included in this module's distribution are several sample programs
720       (located in the samples sub-directory) that illustrate the use of the
721       various random number deviates and other features supported by this
722       module.
723

DIAGNOSTICS

725   WARNINGS
726       Warnings are generated by this module primarily when problems are
727       encountered while trying to obtain random seed data for the PRNGs.
728       This may occur after the module is loaded, after a PRNG object is
729       created, or after calling "srand".
730
731       These seed warnings are not critical in nature.  The PRNG will still be
732       seeded (at a minimum using data such as time() and PID ($$)), and can
733       be used safely.
734
735       The following illustrates how such warnings can be trapped for
736       programmatic handling:
737
738        my @WARNINGS;
739        BEGIN {
740            $SIG{__WARN__} = sub { push(@WARNINGS, @_); };
741        }
742
743        use Math::Random::MT::Auto;
744
745        # Check for standalone PRNG warnings
746        if (@WARNINGS) {
747            # Handle warnings as desired
748            ...
749            # Clear warnings
750            undef(@WARNINGS);
751        }
752
753        my $prng = Math::Random::MT::Auto->new();
754
755        # Check for PRNG object warnings
756        if (@WARNINGS) {
757            # Handle warnings as desired
758            ...
759            # Clear warnings
760            undef(@WARNINGS);
761        }
762
763       •   Failure opening random device '...': ...
764
765           The specified device (e.g., /dev/random) could not be opened by the
766           module.  Further diagnostic information should be included with
767           this warning message (e.g., device does not exist, permission
768           problem, etc.).
769
770       •   Failure setting non-blocking mode on random device '...': ...
771
772           The specified device could not be set to non-blocking mode.
773           Further diagnostic information should be included with this warning
774           message (e.g., permission problem, etc.).
775
776       •   Failure reading from random device '...': ...
777
778           A problem occurred while trying to read from the specified device.
779           Further diagnostic information should be included with this warning
780           message.
781
782       •   Random device '...' exhausted
783
784           The specified device did not supply the requested number of random
785           numbers for the seed.  It could possibly occur if /dev/random is
786           used too frequently.  It will occur if the specified device is a
787           file, and it does not have enough data in it.
788
789       •   Failure creating user-agent: ...
790
791           To utilize the option of acquiring seed data from Internet sources,
792           you need to install the LWP::UserAgent module.
793
794       •   Failure contacting XXX: ...
795
796       •   Failure getting data from XXX: 500 Can't connect to ... (connect:
797           timeout)
798
799           You need to have an Internet connection to utilize "Internet Sites"
800           as random seed sources.
801
802           If you connect to the Internet through an HTTP proxy, then you must
803           set the http_proxy variable in your environment when using the
804           Internet seed sources.  (See "Proxy attributes" in LWP::UserAgent.)
805
806           This module sets a 5 second timeout for Internet connections so
807           that if something goes awry when trying to get seed data from an
808           Internet source, your application will not hang for an inordinate
809           amount of time.
810
811       •   You have exceeded your 24-hour quota for HotBits.
812
813           The HotBits site has a quota on the amount of data you can request
814           in a 24-hour period.  (I don't know how big the quota is.)
815           Therefore, this source may fail to provide any data if used too
816           often.
817
818       •   Failure acquiring Win XP random data: ...
819
820           A problem occurred while trying to acquire seed data from the
821           Window XP random source.  Further diagnostic information should be
822           included with this warning message.
823
824       •   Unknown seeding source: ...
825
826           The specified seeding source is not recognized by this module.
827
828           This error also occurs if you try to use the win32 random data
829           source on something other than MSWin32 or Cygwin on Windows XP.
830
831           See "Seeding Sources" for more information.
832
833       •   No seed data obtained from sources - Setting minimal seed using PID
834           and time
835
836           This message will occur in combination with some other message(s)
837           above.
838
839           If the module cannot acquire any seed data from the specified
840           sources, then data such as time() and PID ($$) will be used to seed
841           the PRNG.
842
843       •   Partial seed - only X of Y
844
845           This message will occur in combination with some other message(s)
846           above.  It informs you of how much seed data was acquired vs. how
847           much was needed.
848
849   ERRORS
850       This module uses "Exception::Class" for reporting errors.  The base
851       error class provided by Object::InsideOut is "OIO".  Here is an example
852       of the basic manner for trapping and handling errors:
853
854        my $obj;
855        eval { $obj = Math::Random::MT::Auto->new(); };
856        if (my $e = OIO->caught()) {
857            print(STDERR "Failure creating new PRNG: $e\n");
858            exit(1);
859        }
860
861       Errors specific to this module have a base class of "MRMA::Args", and
862       have the following error messages:
863
864       •   Missing argument to 'set_seed'
865
866           "set_seed" must be called with an array ref, or a list of integer
867           seed data.
868
869       •   Invalid state vector
870
871           "set_state" was called with an incompatible state vector.  For
872           example, a state vector from a 32-bit integer version of Perl being
873           used with a 64-bit integer version of Perl.
874

PERFORMANCE

876       Under Cygwin, this module is 2.5 times faster than Math::Random::MT,
877       and under Solaris, it's more than four times faster.  (Math::Random::MT
878       fails to build under Windows.)  The file samples/timings.pl, included
879       in this module's distribution, can be used to compare timing results.
880
881       If you connect to the Internet via a phone modem, acquiring seed data
882       may take a second or so.  This delay might be apparent when your
883       application is first started, or when creating a new PRNG object.  This
884       is especially true if you specify multiple "Internet Sites" (so as to
885       get the full seed from them) as this results in multiple accesses to
886       the Internet.  (If /dev/urandom is available on your machine, then you
887       should definitely consider using the Internet sources only as a
888       secondary source.)
889

DEPENDENCIES

891   Installation
892       A 'C' compiler is required for building this module.
893
894       This module uses the following 'standard' modules for installation:
895
896           ExtUtils::MakeMaker
897           File::Spec
898           Test::More
899
900   Operation
901       Requires Perl 5.6.0 or later.
902
903       This module uses the following 'standard' modules:
904
905           Scalar::Util (1.18 or later)
906           Carp
907           Fcntl
908           XSLoader
909
910       This module uses the following modules available through CPAN:
911
912           Object::InsideOut (2.06 or later)
913           Exception::Class (1.22 or later)
914
915       To utilize the option of acquiring seed data from Internet sources, you
916       need to install the LWP::UserAgent module.
917
918       To utilize the option of acquiring seed data from the system's random
919       data source under MSWin32 or Cygwin on Windows XP, you need to install
920       the Win32::API module.
921

BUGS AND LIMITATIONS

923       This module does not support multiple inheritance.
924
925       For Perl prior to 5.10, there is a bug in the overload code associated
926       with 64-bit integers that causes the integer returned by the
927       "->irand()" call to be coerced into a floating-point number.  The
928       workaround in this case is to call "->irand()" directly:
929
930        # my $neg_rand = 0 - $prng;          # Result is a floating-point number
931        my $neg_rand = 0 - $prng->irand();   # Result is an integer number
932
933       The transfer of state vector arrays and serialized objects between 32-
934       and 64-bit integer versions of Perl is not supported, and will produce
935       an 'Invalid state vector' error.
936
937       Please submit any bugs, problems, suggestions, patches, etc. to:
938       <http://rt.cpan.org/Public/Dist/Display.html?Name=Math-Random-MT-Auto>
939

SEE ALSO

941       Math::Random::MT::Auto on MetaCPAN:
942       <https://metacpan.org/release/Math-Random-MT-Auto>
943
944       Code repository: <https://github.com/jdhedden/Math-Random-MT-Auto>
945
946       Sample code in the examples directory of this distribution on CPAN.
947
948       The Mersenne Twister is the (current) quintessential pseudorandom
949       number generator. It is fast, and has a period of 2^19937 - 1.  The
950       Mersenne Twister algorithm was developed by Makoto Matsumoto and Takuji
951       Nishimura.  It is available in 32- and 64-bit integer versions.
952       <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html>
953
954       Wikipedia entries on the Mersenne Twister and pseudorandom number
955       generators, in general:
956       <http://en.wikipedia.org/wiki/Mersenne_twister>, and
957       <http://en.wikipedia.org/wiki/Pseudorandom_number_generator>
958
959       random.org generates random numbers from radio frequency noise.
960       <http://random.org/>
961
962       HotBits generates random number from a radioactive decay source.
963       <http://www.fourmilab.ch/hotbits/>
964
965       RandomNumbers.info generates random number from a quantum optical
966       source.  <http://www.randomnumbers.info/>
967
968       OpenBSD random devices:
969       <http://www.openbsd.org/cgi-bin/man.cgi?query=arandom&sektion=4&apropos=0&manpath=OpenBSD+Current&arch=>
970
971       FreeBSD random devices:
972       <http://www.freebsd.org/cgi/man.cgi?query=random&sektion=4&apropos=0&manpath=FreeBSD+5.3-RELEASE+and+Ports>
973
974       Man pages for /dev/random and /dev/urandom on
975       Unix/Linux/Cygwin/Solaris:
976       <http://www.die.net/doc/linux/man/man4/random.4.html>
977
978       Windows XP random data source:
979       <http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx>
980
981       Fisher-Yates Shuffling Algorithm:
982       <http://en.wikipedia.org/wiki/Shuffling_playing_cards#Shuffling_algorithms>,
983       and shuffle() in List::Util
984
985       Non-uniform random number deviates in Numerical Recipes in C, Chapters
986       7.2 and 7.3: <http://www.library.cornell.edu/nr/bookcpdf.html>
987
988       Inside-out Object Model: Object::InsideOut
989
990       Math::Random::MT::Auto::Range - Subclass of Math::Random::MT::Auto that
991       creates range-valued PRNGs
992
993       LWP::UserAgent
994
995       Math::Random::MT
996
997       Net::Random
998

AUTHOR

1000       Jerry D. Hedden, <jdhedden AT cpan DOT org>
1001
1003       A C-Program for MT19937 (32- and 64-bit versions), with initialization
1004       improved 2002/1/26.  Coded by Takuji Nishimura and Makoto Matsumoto,
1005       and including Shawn Cokus's optimizations.
1006
1007        Copyright (C) 1997 - 2004, Makoto Matsumoto and Takuji Nishimura,
1008         All rights reserved.
1009        Copyright (C) 2005, Mutsuo Saito, All rights reserved.
1010        Copyright 2005 - 2009 Jerry D. Hedden <jdhedden AT cpan DOT org>
1011
1012       Redistribution and use in source and binary forms, with or without
1013       modification, are permitted provided that the following conditions are
1014       met:
1015
1016       1. Redistributions of source code must retain the above copyright
1017          notice, this list of conditions and the following disclaimer.
1018
1019       2. Redistributions in binary form must reproduce the above copyright
1020          notice, this list of conditions and the following disclaimer in the
1021          documentation and/or other materials provided with the distribution.
1022
1023       3. The names of its contributors may not be used to endorse or promote
1024          products derived from this software without specific prior written
1025          permission.
1026
1027       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
1028       IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
1029       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
1030       PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
1031       OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1032       SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1033       LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1034       DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1035       THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1036       (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1037       OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1038
1039        Any feedback is very welcome.
1040        m-mat AT math DOT sci DOT hiroshima-u DOT ac DOT jp
1041        http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
1042
1043
1044
1045perl v5.32.1                      2021-01-27         Math::Random::MT::Auto(3)
Impressum