Random number generator (included): Difference between revisions
Line 63: | Line 63: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
The default RNG used when the <code>random</code> vocabulary is used, is the [[wp:Mersenne twister|Mersenne twister]] algorithm [http://docs.factorcode.org/content/article-random.html]. But there are other RNGs available, including [[wp:SFMT|SFMT]], the system RNG ([[wp:/dev/random|/dev/random]] on Unix) and [[wp:Blum Blum Shub|Blum Blum Shub]]. It's also very easy to implement your own RNG and integrate it into the system. [http://docs.factorcode.org/content/article-random-protocol.html] |
The default RNG used when the <code>random</code> vocabulary is used, is the [[wp:Mersenne twister|Mersenne twister]] algorithm [http://docs.factorcode.org/content/article-random.html]. But there are other RNGs available, including [[wp:SFMT|SFMT]], the system RNG ([[wp:/dev/random|/dev/random]] on Unix) and [[wp:Blum Blum Shub|Blum Blum Shub]]. It's also very easy to implement your own RNG and integrate it into the system. [http://docs.factorcode.org/content/article-random-protocol.html] |
||
=={{header|GAP}}== |
|||
GAP may uses two algorithms : MersenneTwister, or algorithm A in section 3.2.2 of TAOCP (which is the default). On may create several ''random sources'' in parallel, or a global one (based on the TAOCP algorithm). |
|||
<lang gap># Creating a random source |
|||
rs := RandomSource(IsMersenneTwister); |
|||
# Generate a random number between 1 and 10 |
|||
Random(rs, 1, 10); |
|||
# Same with default random source |
|||
Random(1, 10);</lang gap> |
|||
One can get random elements from many objects, including lists |
|||
<lang gap> |
|||
Random([1, 10, 100]); |
|||
# Random permutation of 1..200 |
|||
Random(SymmetricGroup(200)); |
|||
# Random element of Z/23Z : |
|||
Random(Integers mod 23);</lang> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
Revision as of 16:57, 15 November 2010
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to:
- State the type of random number generator algorithm used in a languages built-in random number generator, or omit the language if no random number generator is given as part of the language or its immediate libraries.
- If possible, a link to a wider explanation of the algorithm used should be given.
Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.
The main types of pseudo-random number generator, (PRNG), that are in use are the Linear Congruential Generator, (LCG), and the Generalized Feedback Shift Register, (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits.
LCGs have the advantage of not requiring much state and being very fast to calculate, but produce random numbers with spectral problems. This makes them unsuitable for both Monte Carlo simulation and cryptography. By contrast, GFSRs (of which the Mersenne Twister is a particularly high quality version), require a lot more internal state and are considerably more expensive to compute and initialize (so much so that it is normal to use a LCG or simpler GFSR to drive the initialization); GFSRs tend to have much higher quality spectral properties than LCGs, and are suitable for use in Monte Carlo simulation. Neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
ActionScript
In both Actionscript 2 and 3, the type of pseudorandom number generator is implementation-defined. This number generator is accessed through the Math.random() function, which returns a double greater than or equal to 0 and less than 1.[1][2] In Actionscript 2, the global random() function returns an integer greater than or equal to 0 and less than the given argument, but it is deprecated and not recommended.[3]
ALGOL 68
Details of the random number generator are in the Revised Reports sections: 10.2.1. and 10.5.1.
- 10.2. The standard prelude - 10.2.1. Environment enquiries
- 10.5. The particular preludes and postlude - 10.5.1. The particular preludes
<lang algol68>PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;
¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e. such that -0 <= x < 1 such that the sequence of real values so produced preserves the properties of pseudo-randomness and uniform distribution of the sequence of integral values ¢);
INT ℒ last random := # some initial random number #; PROC ℒ random = ℒ REAL: ℒ next random(ℒ last random);</lang>
Note the suitable "next random number" is suggested to be: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢; ¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e., such that -0 <= x < 1 such that the sequence of real values so produced preserves the properties of pseudo-randomness and uniform distribution of the sequence of integral values ¢);
Algol68 supports random number generation for all precisions available for the specific implementation. The prefix ℒ real indicates all the available precisions. eg short short real, short real, real, long real, long long real etc
For an ASCII implementation and for long real precision these routines would appears as: <lang algol68>PROC long next random = (REF LONG INT a)LONG REAL: # some suitable next random number #; INT long last random := # some initial random number #; PROC long random = LONG REAL: long next random(long last random);</lang>
AutoHotkey
The built-in command Random generates a pseudo-random number using Mersenne Twister "MT19937" (see documentation).
Batch File
Windows batch files can use the %RANDOM%
pseudo-variable which returns a pseudo-random number between 0 and 32767. Behind the scenes this is just a call to the C runtime's rand()
function which uses an LCG in this case:
C
The C standard specifies that there be a pseudorandom number generator in the standard library <stdlib.h> There are no requirements as to the algorithm to be used for generating the random numbers. The standard specifies the interface, and how the rand() function reacts in a multithreaded environment. The rand() function will return an integer in the range 0-RAND_MAX. RAND_MAX must be at least 32767. The returned integers are to be uniformly distributed in this interval.[[4]]
The libraries of many popular C versions implement the rand() function with a linear congruential generator. The specific multiplier and constant varies by implementation, as does which subset of bits within the result is returned as the random number.
As mentioned above, linear congruential generators have problems in their 'randomness' and should not be used where a good quality random number generator is required.
C#
The .NET Random class says that it uses Knuth's subtractive random number generator algorithm.[5]
Clojure
See Java.
Factor
The default RNG used when the random
vocabulary is used, is the Mersenne twister algorithm [6]. But there are other RNGs available, including SFMT, the system RNG (/dev/random on Unix) and Blum Blum Shub. It's also very easy to implement your own RNG and integrate it into the system. [7]
GAP
GAP may uses two algorithms : MersenneTwister, or algorithm A in section 3.2.2 of TAOCP (which is the default). On may create several random sources in parallel, or a global one (based on the TAOCP algorithm). <lang gap># Creating a random source rs := RandomSource(IsMersenneTwister);
- Generate a random number between 1 and 10
Random(rs, 1, 10);
- Same with default random source
Random(1, 10);</lang gap> One can get random elements from many objects, including lists <lang gap> Random([1, 10, 100]);
- Random permutation of 1..200
Random(SymmetricGroup(200));
- Random element of Z/23Z :
Random(Integers mod 23);</lang>
Haskell
The Haskell 98 report specifies an interface for pseudorandom number generation and requires that implementations be minimally statistically robust. It is silent, however, on the choice of algorithm.
Icon and Unicon
Icon and Unicon both use the same linear congruential random number generator x := (x * 1103515245 + 453816694) mod 2^31. Icon uses an initial seed value of 0 and Unicon randomizes the initial seed.
This LCRNG has a number of well documented quirks (see The Icon Analyst issues #26, 28, 38) relating to the choices of an even additive and a power of two modulus. This LCRNG produces two independent sequences of length 2^30 one of even numbers the other odd.
Additionally, the
random provides related procedures including a parametrized LCRNG that defaults to the built-in values.
Inform 7
Inform's random functions are built on the random number generator exposed at runtime by the virtual machine, which is implementation-defined.
J
By default J's ?
primitive (Roll/Deal) uses the Mersenne twister algorithm, but can be set to use a number of other algorithms as detailed on the J Dictionary page for Roll/Deal.
Java
Java's Random
class uses a Linear congruential formula, as described in its documentation. The commonly used Math.random()
uses a Random
object under the hood.
Lua
Lua's math.random()
is an interface to the C rand()
function provided by the OS libc; its implementation varies by platform.
Mathematica
Mathematica 7, by default, uses an Extended Cellular Automaton method ("ExtendedCA") to generate random numbers. The main PRNG functions are RandomReal[]
and RandomInteger[]
You can specify alternative generation methods including the Mersenne Twister and a Linear Congruential Generator (the default earlier versions). Information about random number generation is provided at Mathematica.
MATLAB
MATLAB uses the Mersenne Twister as its default random number generator. Information about how the "rand()" function is utilized is given at MathWorks.
OCaml
OCaml provides a module called Random in its standard library which is a "Linear feedback shift register" pseudo-random number generator (References: Robert Sedgewick, "Algorithms", Addison-Wesley). It is seeded by a MD5-based PRNG.
Oz
Oz provides a binding to the C rand
function as OS.rand
.
PARI/GP
random
uses Richard Brent's xorgens. It's a member of the xorshift class of PRNGs and provides good, fast pseudorandomness (passing the big crush test, unlike the Mersenne twister), but it is not cryptographically strong. As implemented in Pari, its period is "at least
Perl
Perl's rand
function will try and call drand48
, random
or rand
from the C library stdlib.h
in that order.
PHP
PHP has two random number generators: rand
, which uses the underlying C library's rand
function; and mt_rand
, which uses the Mersenne twister algorithm.
PicoLisp
PicoLisp uses a linear congruential generator in the built-in (rand) function, with a multiplier suggested in Knuth's "Seminumerical Algorithms". See the documentation.
PL/I
Values produced by IBM Visualage PL/I compiler built-in random number generator are uniformly distributed between 0 and 1 [0 <= random < 1]
It uses a multiplicative congruential method: <lang PL/I>seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647</lang>
PowerShell
The Get-Random
cmdlet (part of PowerShell 2) uses the .NET-supplied pseudo-random number generator which uses Knuth's subtractive method; see C#.
PureBasic
PureBasic has two random number generators, Random() and CryptRandom(). Random() uses a RANROT type W generator [8]. CryptRandom() uses a very strong PRNG that makes use of a cryptographic safe random number generator for its 'seed', and refreshes the seed if such data is available. The exact method used for CryptRandom() is uncertain.
Python
Python uses the Mersenne twister algorithm accessed via the built-in random module.
Ruby
Ruby's rand
function currently uses the Mersenne twister algorithm, as described in its documentation.
R
For uniform random numbers, R may use Wichmann-Hill, Marsaglia-multicarry, Super-Duper, Mersenne-Twister, or Knuth-TAOCP (both 1997 and 2002 versions), or a user-defined method. The default is Mersenne Twister.
R is able to generate random numbers from a variety of distributions, e.g.
- Beta
- Binomial
- Cauchy
- Chi-Squared
- Exponential
- F
- Gamma
- Geometric
- Hypergeometric
- Logistic
- Log Normal
- Multinomial
- Negative Binomial
- Normal
- Poisson
- Student t
- Uniform
- Weibull
See R help on Random number generation, or in the R system type <lang R>?RNG help.search("Distribution", package="stats")</lang>
Tcl
Tcl uses a linear congruential generator in it's built-in rand()
function. This is seeded by default from the system time, and kept per-interpreter so different security contexts and different threads can't affect each other's generators (avoiding key deployment issues with the rand function from C's math library).
Citations (from Tcl source code):
- S.K. Park & K.W. Miller, “Random number generators: good ones are hard to find,” Comm ACM 31(10):1192-1201, Oct 1988
- W.H. Press & S.A. Teukolsky, “Portable random number generators,” Computers in Physics 6(5):522-524, Sep/Oct 1992.
Ursala
Ursala uses the Mersenne twister algorithm as implemented by the Avram run time system for most purposes, except for arbitrary precision floating point random numbers, which are generated by the urandomb
function from the
mpfr library.