Math::...::Auto(3pm)
π Math::Random::MT::Auto π
okay so bestie, welcome to Math::Random::MT::Auto β it's a Perl module (a "User Contributed Perl Documentation" situation, i.e. a 3pm man page π) all about Auto-seeded Mersenne Twister PRNGs. PRNG = pseudorandom number generator, in case you were like "huh?" β it's the thing that makes random numbers for you. π₯
β¨ VERSION β¨
This documentation refers to Math::Random::MT::Auto version 6.23. slay. π
πΈ SYNOPSIS πΈ
here's the whole vibe, look at her go:
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. like, truly a queen of volume. π
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.) she seeds herself, no cap. π
π Random Number Deviates π
In addition to integer and floating-point uniformly-distributed random number deviates (i.e., irand and rand), this module implements the following non-uniform deviates as found in Numerical Recipes in C:
- Gaussian (normal)
- Exponential
- Erlang (gamma of integer order)
- Poisson
- Binomial
π Shuffling π
This module also provides a subroutine/method for shuffling data based on the Fisher-Yates shuffling algorithm. iconic algorithm tbh.
β Support for 64-bit Integers β
If Perl has been compiled to support 64-bit integers (do perl -V and look for use64bitint=define), 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 irand, and used by get_seed and set_seed will be sized accordingly.
Programmatically, the size of Perl's integers can be determined using the Config module:
use Config;
print("Integers are $Config{'uvsize'} bytes in length\n");
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.) π rip to that one.
π 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. she does it for you, bestie, because she loves you. π«Ά
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. do not skip this, fr fr.
π 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 π
π 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.
(I would be interested to hear about other random data sources for possible inclusion in future versions of this module.) ok so if you know a guy who knows a guy... π
π Random Devices π
Most OSs offer some sort of device for acquiring random numbers. The most common are /dev/urandom and /dev/random. You can specify the use of these devices for acquiring the seed for the PRNG when you declare this module:
use Math::Random::MT::Auto '/dev/urandom';
# or
my $prng = Math::Random::MT::Auto->new('SOURCE' => '/dev/random');
or they can be specified when using srand.
srand('/dev/random');
# or
$prng->srand('/dev/urandom');
The devices are accessed in non-blocking mode so that if there is insufficient data when they are read, the application will not hang waiting for more. no sitting around waiting for your ex to text back energy. π
π¦ 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).
srand('C:\\Temp\\RANDOM.DAT');
# or
$prng->srand('/tmp/random.dat');
π 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.
use Math::Random::MT::Auto 'random_org';
# or
use Math::Random::MT::Auto 'hotbits';
# or
use Math::Random::MT::Auto 'rn_info';
If you connect to the Internet through an HTTP proxy, then you must set the http_proxy variable in your environment when using these sources. (See "Proxy attributes" in LWP::UserAgent.)
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:
my $prng = Math::Random::MT::Auto->new('SOURCE' => ['hotbits',
'hotbits']);
or specify multiple sources:
use Math::Random::MT::Auto qw(rn_info hotbits random_org);
π§ Windows XP Random Data π§
Under MSWin32 or Cygwin on Windows XP, you can acquire random seed data from the system.
use Math::Random::MT::Auto 'win32';
To utilize this option, you must have the Win32::API module installed.
β¨ 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.
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('SOURCE' => \&MySeeder);
The default list of seeding sources is determined when the module is loaded. Under MSWin32 or Cygwin on Windows XP, win32 is added to the list if Win32::API is available. Otherwise, /dev/urandom and then /dev/random are checked. The first one found is added to the list. Finally, random_org is added.
For the functional interface to the standalone PRNG, these defaults can be overridden by specifying the desired sources when the module is declared, or through the use of the srand subroutine. Similarly for the OO interface, they can be overridden in the ->new() method when the PRNG is created, or later using the srand method.
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:
# Get at most 1024 bytes from random.org
# Finish the seed using data from /dev/urandom
use Math::Random::MT::Auto 'random_org' => (1024 / $Config{'uvsize'}),
'/dev/urandom';
π Delayed Seeding π
Normally, the standalone PRNG is automatically seeded when the module is loaded. This behavior can be modified by supplying the :!auto (or :noauto) flag when the module is declared. (The PRNG will still be seeded using data such as time() and PID ($$), just in case.) When the :!auto option is used, the srand subroutine should be imported, and then run before calling any of the random number deviates.
use Math::Random::MT::Auto qw(rand srand :!auto);
...
srand();
...
my $rn = rand(10);
β 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 π
my $obj = $MRMA::PRNG;β$MRMA::PRNGis the object that represents the standalone PRNG.
...and bestie, there's more coming, don't go anywhere π
β¨ OBJECT CREATION β¨
okay so bestie, the OO interface is where this module really pops off β it lets you spin up as many independent PRNGs as you want, each one doing its own thing π no clones unless you ask for one.
And here's a lil tip: if your app is only ever gonna use the OO interface, declare the module with the :!auto flag so it doesn't go seeding the standalone PRNG behind your back:
use Math::Random::MT::Auto ':!auto';
Math::Random::MT::Auto->new
my $prng = Math::Random::MT::Auto->new( %options );
Makes you a brand new PRNG π. With no options at all, it gets seeded using the default sources that were figured out back when the module was loaded, or whatever the srand subroutine was last handed.
'STATE' => $prng_stateβ sets the fresh new PRNG straight to the state you give it. After that it acts like a total clone of the RPNG that state came from (specifically, the RPNG as it was at the moment that state was grabbed).
heads up babes: when you use the STATE option, every other option is just stored β none of them actually get acted upon π
'SEED' => $seed_array_refβ if theSTATEoption isn't in play, this seeds the brand new PRNG with the seed data you supply. IfSTATEis in play, the seed data just gets copied over to the new object, that's it.'SOURCE' => 'source''SOURCE' => ['source', ...]β tells it which seeding source(s) to use for the PRNG. If you're not using theSTATEorSEEDoptions, seed data gets fetched right away from the sources you named and used to seed the PRNG. The source list gets kept around for thesrandmethod to use later, and you can swap the whole list out by callingsrand. Also,'SOURCES','SRC'and'SRCS'all work as synonyms for'SOURCE'β¨
And psa: those options above also work in lowercase and mixed-case (like 'Seed', 'src', etc.) π
$obj->new
my $prng2 = $prng1->new( %options );
Creates a new PRNG, same exact way as Math::Random::MT::Auto->new does it. no notes.
$obj->clone
my $prng2 = $prng1->clone();
Makes a new PRNG that's a copy of the PRNG you called it on. twin energy fr fr π―
π SUBROUTINES/METHODS π
Here's the deal, bestie β every function down below has two modes and the vibes are different depending on which one you use:
- Call it as a subroutine β it operates on the standalone PRNG. Like:
my $rand = rand();
- Call it as a method β it operates on the referenced PRNG object. Like:
my $rand = $prng->rand();
For brevity (and because I love you), only the functional usage examples are shown below β¨
rand
my $rn = rand();
my $rn = rand($num);
Behaves exactly like Perl's built-in rand, handing you back a number uniformly distributed in [0, $num). ($num defaults to 1.)
NOTE: if you still need to reach Perl's built-inrandfunction, you can grab it withCORE::rand().
irand
my $int = irand();
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.
This is the fastest way to get random numbers out of this module. speed demon behavior, we stan π
shuffle
my @shuffled = shuffle($data, ...);
my @shuffled = shuffle(@data);
Returns an array of your supplied arguments in a random ordering (i.e., shuffled), using the Fisher-Yates shuffling algorithm. It can also be called to hand back an array reference:
my $shuffled = shuffle($data, ...);
my $shuffled = shuffle(@data);
And if you call it with a single array reference (the fastest method btw), it shuffles the contents of that array in situ:
shuffle(\@data);
gaussian
my $gn = gaussian();
my $gn = gaussian($sd);
my $gn = gaussian($sd, $mean);
Returns floating-point random numbers from a Gaussian (normal) distribution β you know, the pretty bell curve one π. Called with no arguments, it uses a standard deviation of 1 and a mean of 0. Otherwise, your supplied argument(s) get used for the standard deviation, and the mean.
exponential
my $xn = exponential();
my $xn = exponential($mean);
Returns floating-point random numbers from an exponential distribution π. With no arguments, the distribution uses a mean of 1. Otherwise, your supplied argument gets used for the mean.
An example of an exponential distribution is the time interval between independent Poisson-random events, like radioactive decay β’οΈ. In that case, the mean is the average time between events. This is called the mean life for radioactive decay, and its inverse is the decay constant (which represents the expected number of events per unit time). The well known term half-life is given by mean * ln(2).
erlang
my $en = erlang($order);
my $en = erlang($order, $mean);
Returns floating-point random numbers from an Erlang distribution of a specified order. The order has to be a positive integer (> 0). The mean, if you don't specify it, defaults to 1.
The Erlang distribution is the distribution of the sum of $order independent identically distributed random variables, each one having an exponential distribution. (It's a special case of the gamma distribution where $order is a positive integer.) When $order = 1, it's literally just the exponential distribution. It's named after A. K. Erlang, who cooked it up to predict waiting times in queuing systems πΆπΆπΆ iykyk.
poisson
my $pn = poisson($mean);
my $pn = poisson($rate, $time);
Returns integer random numbers (>= 0) from a Poisson distribution of a specified mean (rate * time = mean). The mean has to be a positive value (> 0).
The Poisson distribution predicts the probability of the number of Poisson-random events happening in a fixed time, as long as those events occur with a known average rate. Examples of events you can model as Poisson distributions include:
- The number of decays from a radioactive sample within a given time period.
- The number of cars that pass a certain point on a road within a given time period.
- The number of phone calls to a call center per minute.
- The number of road kill found per a given length of road. π
binomial
my $bn = binomial($prob, $trials);
Returns integer random numbers (>= 0) from a binomial distribution. The probability ($prob) has to be between 0.0 and 1.0 (inclusive), and the number of trials has to be >= 0.
The binomial distribution is the discrete probability distribution of the number of successes in a sequence of $trials independent Bernoulli trials (i.e., yes/no experiments), each one succeeding with probability $prob.
If the number of trials is very large, the binomial distribution may be approximated by a Gaussian distribution. And if the average number of successes is small ($prob * $trials < 1), then the binomial distribution can be approximated by a Poisson distribution. math girlies rise up π
srand
srand();
srand('source', ...);
This (re)seeds the PRNG β¨. You can call it anytime you want a reseed (though normally you won't need to β it's giving overkill).
When the :!auto flag is in use, you should call the srand subroutine before any other access to the standalone PRNG. do not skip this step bestie, fr fr.
Called with no arguments, the previously determined/specified seeding source(s) get used to seed the PRNG.
Optionally, you can supply seeding sources as arguments, exactly like using the 'SOURCE' option. (These sources get saved and used again if srand is later called with no arguments.)
# Get 250 integers of seed data from Hotbits,
# and then get the rest from /dev/random
srand('hotbits' => 250, '/dev/random');
If you call it with integer data (a list of one or more value, or an array of values), or a reference to an array of integers, those data get passed to set_seed for use in reseeding the PRNG.
NOTE: if you still need to reach Perl's built-insrandfunction, you can do so usingCORE::srand($seed).
get_seed
my @seed = get_seed();
# or
my $seed = get_seed();
Returns an array or an array reference containing the seed last sent to the PRNG π±.
NOTE: changing the data in that array will not cause any changes in the PRNG (i.e., it will not reseed it). You need to usesrandorset_seedfor that. don't try to be sneaky π
set_seed
set_seed($seed, ...);
set_seed(@seed);
set_seed(\@seed);
Called with integer data (a list of one or more value, or an array of values), or a reference to an array of integers, those data get used to reseed the PRNG.
Together with get_seed, set_seed may be useful for setting up identical sequences of random numbers based on the same seed. π reproducible queen behavior.
It's possible to seed the PRNG with more than 19968 bits of data (312 64-bit integers or 624 32-bit integers). However, doing so does not make the PRNG "more random", because 19968 bits more than covers all the possible PRNG state vectors.
get_state
my @state = get_state();
# or
my $state = get_state();
Returns an array (in list context) or an array reference (in scalar context) containing the current state vector of the PRNG.
Note that the state vector is not a full serialization of the PRNG. (See "Serialization" below.) π«Ά
set_state
set_state(@state);
# or
set_state($state);
Sets a PRNG to the state contained in an array or array reference that contains a state you previously got with get_state.
# 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.
CAUTION: it should go without saying, but do not modify the values in the state vector you got fromget_state. Doing that and then feeding it toset_statewould be (to say the least) naughty. π₯ we do not do that here.
π« INSIDE-OUT OBJECTS π«
So Math::Random::MT::Auto builds its PRNG objects on top of Object::InsideOut, and because of that you get a whole lil' bundle of extra superpowers. Here's the tea, bestie β¨
Cloning
You can make a copy of any PRNG object with the ->clone() method, no cap π
my $prng2 = $prng->clone();
Want the full lore? Go read "Object Cloning" in Object::InsideOut π«Ά
Serialization
PRNG objects can be serialized with the ->dump() method, bestie, they get a lil' glow-up into data:
my $array_ref = $prng->dump();
# or
my $string = $prng->dump(1);
Then you can pump that serialized lil' guy right back into a PRNG object:
my $prng2 = Object::InsideOut->pump($array_ref);
More details live in "Object Serialization" in Object::InsideOut π
Serialization via Storable is supported too:
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);
And if you want even more, "Storable" in Object::InsideOut has you covered π
NOTE: Code refs cannot be serialized. So literally any "User-defined Seeding Source" subroutines you used alongside srand will get filtered out of the serialized results. Gone. Not invited to the party π
Coercion
Obsessed with this one actually β the overload mechanism supports all kinds of object coercion. Like, 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 happens by calling ->irand() on the object, and then returning the integer it got as the coerced result. Iconic behavior tbh π
A similar overload coercion goes down when the object shows up in a numeric context:
my $neg_rand = 0 - $prng;
(See "BUGS AND LIMITATIONS" about numeric overloading on 64-bit integer Perls before 5.10. Just a heads up π«£)
In a boolean context, the coercion returns true or false depending on whether ->irand() returns an odd or an even result. Coin flip energy fr fr πͺ
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};
Okay so this might not be all that useful on its own, so you can just call the ->array() method directly with an integer argument for how many random integers you want π
# Get 20 random integers
my @rands = @{$prng->array(20)};
And finally β the main character move β a PRNG object can be used to produce a code reference that returns random integers every single time it's invoked:
my $rand = \&{$prng};
my $int = &$rand;
More on this in "Object Coercion" in Object::InsideOut π
Thread Support
Math::Random::MT::Auto gives you thread support to the extent documented in "THREAD SUPPORT" in Object::InsideOut.
In a threaded application (so, use threads;), the standalone PRNG and all the PRNG objects from one thread get copied and made available in a child thread. Copy-paste but make it genetics π§¬
Wanna enable sharing PRNG objects between threads? Do this 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. So you cannot use "User-defined Seeding Source" subroutines in conjunction withsrandwhenuse threads::shared;is in effect. Periodt π
Depending on your needs, when you're using threads but not enabling thread-sharing of PRNG objects like above, you might wanna do 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 differ π
use threads;
use Math::Random:MT::Auto qw(irand srand);
my $prng = Math::Random:MT::Auto->new();
sub thr_code
{
srand();
$prng->srand();
....
}
πΈ EXAMPLES πΈ
Cloning the standalone PRNG to an object
use Math::Random::MT::Auto qw(get_state);
my $prng = Math::Random::MT::Auto->new('STATE' => scalar(get_state()));
or using the standalone PRNG object directly:
my $prng = $Math::Random::MT::Auto::SA_PRNG->clone();
The standalone PRNG and the PRNG object will now return the same sequence of pseudorandom numbers. Twin flames, honestly π
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. Go peek, they ate π₯
π©Ί DIAGNOSTICS π©Ί
WARNINGS
Warnings get generated by this module mostly when problems are encountered while trying to obtain random seed data for the PRNGs. This may happen after the module is loaded, after a PRNG object is created, or after calling srand. Timing is giving chaos tbh π
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. So like, breathe, you're fine π«Ά
Here's how you can trap those warnings 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);
}
Now the warning hall of fame, one by one π
Failure opening random device '...': ...β The specified device (like/dev/random) could not be opened by the module. Further diagnostic information should be included with this warning message (for instance: device does not exist, permission problem, etc.).Failure setting non-blocking mode on random device '...': ...β The specified device could not be set to non-blocking mode. Further diagnostic information should be included with this warning message (for instance: permission problem, etc.).Failure reading from random device '...': ...β A problem occurred while trying to read from the specified device. Further diagnostic information should be included with this warning message.Random device '...' exhaustedβ The specified device did not supply the requested number of random numbers for the seed. It could possibly occur if/dev/randomis used too frequently. It will occur if the specified device is a file and it does not have enough data in it.Failure creating user-agent: ...β To utilize the option of acquiring seed data from Internet sources, you need to install the LWP::UserAgent module.Failure contacting XXX: ...Failure getting data from XXX: 500 Can't connect to ... (connect: timeout)β You need to have an Internet connection to utilize "Internet Sites" as random seed sources.
If you connect to the Internet through an HTTP proxy, then you must set the http_proxy variable in your environment when using the Internet seed sources. (See "Proxy attributes" in LWP::UserAgent.)
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. Considerate king behavior π
You have exceeded your 24-hour quota for HotBits.β 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.Failure acquiring Win XP random data: ...β A problem occurred while trying to acquire seed data from the Window XP random source. Further diagnostic information should be included with this warning message.Unknown seeding source: ...β The specified seeding source is not recognized by this module.
This error also occurs if you try to use the win32 random data source on something other than MSWin32 or Cygwin on Windows XP.
See "Seeding Sources" for more information.
No seed data obtained from sources - Setting minimal seed using PID and timeβ This message will occur in combination with some other message(s) above.
If the module cannot acquire any seed data from the specified sources, then data such as time() and PID ($$) will be used to seed the PRNG.
Partial seed - only X of Yβ 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. Like a progress bar but it's a warning π
ERRORS
This module uses Exception::Class for reporting errors. The base error class provided by Object::InsideOut is OIO. Here's 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 they come with the following error messages:
Missing argument to 'set_seed'βset_seedmust be called with an array ref, or a list of integer seed data. No argument, no seed, bestie π€Invalid state vectorβset_statewas 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. Not compatible, not the vibe π
β‘ 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, so, y'know.) The file samples/timings.pl, included in this module's distribution, can be used to compare timing results. Speed demon behavior, we love to see it ποΈπ¨
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) since 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.) Delay era, unfortunately π
π DEPENDENCIES π
okay bestie, before you go running this thing, here's the shopping list. nothing wild, but like, read it.
π οΈ Installation
you need a 'C' compiler to build this module. yes, a real one. no, we're not doing it in pure Perl, sorry babes. π«Ά
the following 'standard' modules get used for the install:
ExtUtils::MakeMaker
File::Spec
Test::More
π Operation
needs Perl 5.6.0 or later. anything older and it's giving not supported.
this module uses these 'standard' modules:
Scalar::Util (1.18 or later)
Carp
Fcntl
XSLoader
and these ones, which you gotta grab from CPAN:
Object::InsideOut (2.06 or later)
Exception::Class (1.22 or later)
also!! if you wanna use the option of pulling seed data from Internet sources, you need LWP::UserAgent installed. π
and if you wanna use the option of grabbing seed data from the system's random data source underMSWin32orCygwinon Windows XP, you needWin32::API. πͺ
π BUGS AND LIMITATIONS π
listen. we love her, but she has β¨quirksβ¨.
- this module does not support multiple inheritance. periodt.
- for Perl prior to 5.10, there's 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, bestie, 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
- transferring state vector arrays and serialized objects between 32- and 64-bit integer versions of Perl? not supported. it will throw an
'Invalid state vector'error at you. no cap. π
please submit any bugs, problems, suggestions, patches, etc. to: <http://rt.cpan.org/Public/Dist/Display.html?Name=Math-Random-MT-Auto>
π SEE ALSO π
the lore, the links, the whole aesthetic:
Math::Random::MT::Autoon MetaCPAN:<https://metacpan.org/release/Math-Random-MT-Auto>- Code repository:
<https://github.com/jdhedden/Math-Random-MT-Auto> - Sample code in the examples directory of this distribution on CPAN.
okay so the Mersenne Twister is the (current) quintessential pseudorandom number generator. it's fast, and its period is 2^19937 - 1. the algorithm was developed by Makoto Matsumoto and Takuji Nishimura, and it comes in 32- and 64-bit integer versions. iconic. <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.orggenerates random numbers from radio frequency noise.<http://random.org/>HotBitsgenerates random numbers from a radioactive decay source.<http://www.fourmilab.ch/hotbits/>RandomNumbers.infogenerates random numbers 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/randomand/dev/urandomon 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>, andshuffle()inList::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 ofMath::Random::MT::Autothat creates range-valued PRNGsLWP::UserAgentMath::Random::MTNet::Random
π AUTHOR π
Jerry D. Hedden, <jdhedden AT cpan DOT org>
we stan. π
π 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:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- 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.
- 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
and that's the whole page, bestie!! π¦ this lil masterpiece is served up as perl v5.42.3 documentation dated 2026-08-20, filed under Math::...::Auto(3pm) β so if you ever forget what version of the manpage you're reading, now you know. go forth and generate some chaos. love u, byeee πβ¨
π¦ where this page comes from
- ubuntu stonking: libmath-random-mt-auto-perl 6.23-2build5 Β· BSD-3-Clause
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms