Syntax-K

Know-How für Ihr Projekt

Perl Documentation

NAME

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

VERSION

This documentation refers to Math::Random::MT::Auto version 6.22

SYNOPSIS

use strict;
use warnings;
use Math::Random::MT::Auto qw(rand irand shuffle gaussian),
                           '/dev/urandom' => 256,
                           'random_org';
# Functional interface
my $die_roll = 1 + int(rand(6));
my $coin_flip = (irand() & 1) ? 'heads' : 'tails';
my @deck = shuffle(1 .. 52);
my $rand_IQ = gaussian(15, 100);
# OO interface
my $prng = Math::Random::MT::Auto->new('SOURCE' => '/dev/random');
my $angle = $prng->rand(360);
my $decay_interval = $prng->exponential(12.4);

DESCRIPTION

The Mersenne Twister is a fast pseudorandom number generator (PRNG) that is capable of providing large volumes (> 10^6004) of "high quality" pseudorandom data to applications that may exhaust available "truly" random data sources or system-provided PRNGs such as rand.

This module provides PRNGs that are based on the Mersenne Twister. There is a functional interface to a single, standalone PRNG, and an OO interface (based on the inside-out object model as implemented by the Object::InsideOut module) for generating multiple PRNG objects. The PRNGs are normally self-seeding, automatically acquiring a (19968-bit) random seed from user-selectable sources. (Manual seeding is optionally available.)

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.)

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:

use strict;
use warnings;
use Math::Random::MT::Auto 'rand';

and then just use "rand" as you would normally. You don't even need to bother seeding the PRNG (i.e., you don't need to call "srand"), as that gets done automatically when the module is loaded by Perl.

If you need multiple PRNGs, then use the OO interface:

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();

CAUTION: If you want to require this module, see the "Delayed Importation" section for important information.

MODULE DECLARATION

The module must always be declared such that its ->import() method gets called:

use Math::Random::MT::Auto;            # Correct
#use Math::Random::MT::Auto ();        # Does not work because
                                       #   ->import() does not get invoked

Subroutine Declarations

By default, this module does not automatically export any of its subroutines. If you want to use the standalone PRNG, then you should specify the subroutines you want to use when you declare the module:

use Math::Random::MT::Auto qw(rand irand shuffle gaussian
                              exponential erlang poisson binomial
                              srand get_seed set_seed get_state set_state);

Without the above declarations, it is still possible to use the standalone PRNG by accessing the subroutines using their fully-qualified names. For example:

my $rand = Math::Random::MT::Auto::rand();

Module Options

Delayed Importation

If you want to delay the importation of this module using require, then you must execute its ->import() method to complete the module's initialization:

eval {
    require Math::Random::MT::Auto;
    # You may add options to the import call, if desired.
    Math::Random::MT::Auto->import();
};

STANDALONE PRNG OBJECT

OBJECT CREATION

The OO interface for this module allows you to create multiple, independent PRNGs.

If your application will only be using the OO interface, then declare this module using the :!auto flag to forestall the automatic seeding of the standalone PRNG:

use Math::Random::MT::Auto ':!auto';

SUBROUTINES/METHODS

When any of the functions listed below are invoked as subroutines, they operates with respect to the standalone PRNG. For example:

my $rand = rand();

When invoked as methods, they operate on the referenced PRNG object:

my $rand = $prng->rand();

For brevity, only usage examples for the functional interface are given below.

INSIDE-OUT OBJECTS

By using Object::InsideOut, Math::Random::MT::Auto's PRNG objects support the following capabilities:

Cloning

Copies of PRNG objects can be created using the ->clone() method.

my $prng2 = $prng->clone();

See "Object Cloning" in Object::InsideOut for more details.

Serialization

PRNG objects can be serialized using the ->dump() method.

my $array_ref = $prng->dump();
  # or
my $string = $prng->dump(1);

Serialized object can then be converted back into PRNG objects:

my $prng2 = Object::InsideOut->pump($array_ref);

See "Object Serialization" in Object::InsideOut for more details.

Serialization using Storable is also supported:

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);

See "Storable" in Object::InsideOut for more details.

NOTE: Code refs cannot be serialized. Therefore, any "User-defined Seeding Source" subroutines used in conjunction with "srand" will be filtered out from the serialized results.

Coercion

Various forms of object coercion are supported through the overload mechanism. For instance, you can to use a PRNG object directly in a string:

my $prng = Math::Random::MT::Auto->new();
print("Here's a random integer: $prng\n");

The stringification of the PRNG object is accomplished by calling ->irand() on the object, and returning the integer so obtained as the coerced result.

A similar overload coercion is performed when the object is used in a numeric context:

my $neg_rand = 0 - $prng;

(See "BUGS AND LIMITATIONS" regarding numeric overloading on 64-bit integer Perls prior to 5.10.)

In a boolean context, the coercion returns true or false based on whether the call to ->irand() returns an odd or even result:

if ($prng) {
    print("Heads - I win!\n");
} else {
    print("Tails - You lose.\n");
}

In an array context, the coercion returns a single integer result:

my @rands = @{$prng};

This may not be all that useful, so you can call the ->array() method directly with a integer argument for the number of random integers you'd like:

# Get 20 random integers
my @rands = @{$prng->array(20)};

Finally, a PRNG object can be used to produce a code reference that will return random integers each time it is invoked:

my $rand = \&{$prng};
my $int = &$rand;

See "Object Coercion" in Object::InsideOut for more details.

Thread Support

Math::Random::MT::Auto provides thread support to the extent documented in "THREAD SUPPORT" in Object::InsideOut.

In a threaded application (i.e., use threads;), the standalone PRNG and all the PRNG objects from one thread will be copied and made available in a child thread.

To enable the sharing of PRNG objects between threads, do the following in your application:

use threads;
use threads::shared;
BEGIN {
    $Math::Random::MT::Auto::shared = 1;
}
use Math::Random::MT::Auto ...;

NOTE: Code refs cannot be shared between threads. Therefore, you cannot use "User-defined Seeding Source" subroutines in conjunction with "srand" when use threads::shared; is in effect.

Depending on your needs, when using threads, but not enabling thread-sharing of PRNG objects as per the above, you may want to perform an srand call on the standalone PRNG and/or your PRNG objects inside the threaded code so that the pseudorandom number sequences generated in each thread differs.

use threads;
use Math::Random:MT::Auto qw(irand srand);
my $prng = Math::Random:MT::Auto->new();
sub thr_code
{
    srand();
    $prng->srand();
    ....
}

EXAMPLES

Included in this module's distribution are several sample programs (located in the samples sub-directory) that illustrate the use of the various random number deviates and other features supported by this module.

DIAGNOSTICS

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 PRNG object is created, or after calling "srand".

These seed warnings are not critical in nature. The PRNG will still be seeded (at a minimum using data such as time() and PID ($$)), and can be used safely.

The following illustrates how such warnings can be trapped for programmatic handling:

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);
}

ERRORS

This module uses Exception::Class for reporting errors. The base error class provided by Object::InsideOut is OIO. Here is an example of the basic manner for trapping and handling errors:

my $obj;
eval { $obj = Math::Random::MT::Auto->new(); };
if (my $e = OIO->caught()) {
    print(STDERR "Failure creating new PRNG: $e\n");
    exit(1);
}

Errors specific to this module have a base class of MRMA::Args, and have the following error messages:

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 samples/timings.pl, included in this module's distribution, can be used to compare timing results.

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 PRNG object. This is especially true if you specify multiple "Internet Sites" (so as to get the full seed from them) as this results in multiple accesses to the Internet. (If /dev/urandom is available on your machine, then you should definitely consider using the Internet sources only as a secondary source.)

DEPENDENCIES

Installation

A 'C' compiler is required for building this module.

This module uses the following 'standard' modules for installation:

Operation

Requires Perl 5.6.0 or later.

This module uses the following 'standard' modules:

This module uses the following modules available through CPAN:

To utilize the option of acquiring seed data from Internet sources, you need to install the LWP::UserAgent module.

To utilize the option of acquiring seed data from the system's random data source under MSWin32 or Cygwin on Windows XP, you need to install the Win32::API module.

BUGS AND LIMITATIONS

This module does not support multiple inheritance.

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 ->irand() call to be coerced into a floating-point number. The workaround in this case is to call ->irand() directly:

# my $neg_rand = 0 - $prng;          # Result is a floating-point number
my $neg_rand = 0 - $prng->irand();   # Result is an integer number

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.

Please submit any bugs, problems, suggestions, patches, etc. to: http://rt.cpan.org/Public/Dist/Display.html?Name=Math-Random-MT-Auto

SEE ALSO

Math::Random::MT::Auto Discussion Forum on CPAN: http://www.cpanforum.com/dist/Math-Random-MT-Auto

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. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html

Wikipedia entries on the Mersenne Twister and pseudorandom number generators, in general: http://en.wikipedia.org/wiki/Mersenne_twister, and http://en.wikipedia.org/wiki/Pseudorandom_number_generator

random.org generates random numbers from radio frequency noise. http://random.org/

HotBits generates random number from a radioactive decay source. http://www.fourmilab.ch/hotbits/

RandomNumbers.info generates random number from a quantum optical source. http://www.randomnumbers.info/

OpenBSD random devices: http://www.openbsd.org/cgi-bin/man.cgi?query=arandom&sektion=4&apropos=0&manpath=OpenBSD+Current&arch=

FreeBSD random devices: http://www.freebsd.org/cgi/man.cgi?query=random&sektion=4&apropos=0&manpath=FreeBSD+5.3-RELEASE+and+Ports

Man pages for /dev/random and /dev/urandom on Unix/Linux/Cygwin/Solaris: http://www.die.net/doc/linux/man/man4/random.4.html

Windows XP random data source: http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx

Fisher-Yates Shuffling Algorithm: http://en.wikipedia.org/wiki/Shuffling_playing_cards#Shuffling_algorithms, and shuffle() in List::Util

Non-uniform random number deviates in Numerical Recipes in C, Chapters 7.2 and 7.3: http://www.library.cornell.edu/nr/bookcpdf.html

Inside-out Object Model: Object::InsideOut

Math::Random::MT::Auto::Range - Subclass of Math::Random::MT::Auto that creates range-valued PRNGs

LWP::UserAgent

Math::Random::MT

Net::Random

AUTHOR

Jerry D. Hedden, pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp

COPYRIGHT AND LICENSE

A C-Program for MT19937 (32- and 64-bit versions), with initialization improved 2002/1/26. Coded by Takuji Nishimura and Makoto Matsumoto, and including Shawn Cokus's optimizations.

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 <jdhedden AT cpan DOT org>

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

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.

3. The names of its contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

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