Random number generator (included): Difference between revisions
Added Nemerle |
m →{{header|PARI/GP}}: quote |
||
Line 146:
=={{header|PARI/GP}}==
<code>random</code> uses Richard Brent's [http://wwwmaths.anu.edu.au/~brent/random.html 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 <math>2^{4096}-1".</math>
=={{header|Perl}}==
|
Revision as of 02:59, 9 July 2011
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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]
Ada
The Ada standard defines Random Number Generation in Annex A.5.2. There are two kinds of RNGs, Ada.Numerics.Float_Random for floating point values from 0.0 to 1.0, and Ada.Numerics.Discrete_Random for pseudo-random values of enumeration types (including integer types). It provides facilities to initialize the generator and to save it's state.
The standard requires the implementation to uniformly distribute over the range of the result type.
The used algorithm is implementation defined. The standard says: "To enable the user to determine the suitability of the random number generators for the intended application, the implementation shall describe the algorithm used and shall give its period, if known exactly, or a lower bound on the period, if the exact period is unknown."
95 RM - A.5.2 Random Number Generation 2005 RM - A.5.2 Random Number Generation
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.
D
From std.random:
The generators feature a number of well-known and well-documented methods of generating random numbers. An overall fast and reliable means to generate random numbers is the Mt19937 generator, which derives its name from "Twister with a period of 2 to the power of 19937". In memory-constrained situations, congruential generators such as MinstdRand0 and MinstdRand might be useful. The standard library provides an alias Random for whichever generator it considers the most fit for the target environment.
Delphi
According to Wikipedia, Delphi uses a Linear Congruential Generator.
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). One 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> 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>
Go
Go has two packages providing random numbers.
- Rand has general purpose random number support. The code attributes the algorithm to DP Mitchell and JA Reeds, and with what little I know, I would guess it's an GFSR. (It uses a large array commented "feeback register" and has variables named "tap" and "feed.")
- Crypto/rand says it "implements a cryptographically secure pseudorandom number generator." I think though it should say that it accesses a cryptographically secure pseudorandom number generator. It uses /dev/urandom on Linix and similar systems and the CryptGenRandom API on Windows.
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.
Nemerle
Uses .Net Random class; so, as mentioned under C#, above, implements Knuth's subtractive random number generator algorithm. Random class documentation at MSDN.
OCaml
OCaml provides a module called Random in its standard library. It used to be a "Linear feedback shift register" pseudo-random number generator (References: Robert Sedgewick, "Algorithms", Addison-Wesley). It is now (as of version 3.12.0) a "lagged-Fibonacci F(55, 24, +) with a modified addition function to enhance the mixing of bits." It passes the Diehard test suite.
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 Failed to parse (syntax error): {\displaystyle 2^{4096}-1".}
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>
Seed7
Seed7 uses a linear congruential generator to compute pseudorandom numbers. Usually random number generators deliver a random value in a fixed range, The Seed7 function rand(low, high) delivers a random number in the requested range [low, high]. Seed7 overloads the rand functions for the types char, boolean, bigInteger, float and others.
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.
ZX Spectrum Basic
The ZX Spectrum uses a pseudorandom number generator that utilizes values stored in the sytem ROM. The random numbers produced will repeat after 65535 iterations.
- Programming Tasks
- Solutions by Programming Task
- ActionScript
- Ada
- ALGOL 68
- AutoHotkey
- Batch File
- C
- C sharp
- Clojure
- D
- Delphi
- Factor
- GAP
- Go
- Haskell
- Icon
- Unicon
- Icon Programming Library
- Inform 7
- J
- Java
- Lua
- Mathematica
- MATLAB
- Nemerle
- OCaml
- Oz
- PARI/GP
- Perl
- PHP
- PicoLisp
- PL/I
- PowerShell
- PureBasic
- Python
- Ruby
- R
- Seed7
- Tcl
- Ursala
- Bc/Omit
- Dc/Omit
- Sed/Omit
- Unlambda/Omit
- ZX Spectrum Basic
- Randomness
- Pages with math errors
- Pages with math render errors