Random number generator (included)
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 language's builtin random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.
 If possible, give a link to a wider explanation of the algorithm used.
Note: the task is not to create an RNG, but to report on the languages inbuilt RNG that would be the most likely RNG used.
The main types of pseudorandom 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.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
Contents
 1 8th
 2 ActionScript
 3 Ada
 4 ALGOL 68
 5 AutoHotkey
 6 AWK
 7 BASIC
 8 Batch File
 9 BBC BASIC
 10 Befunge
 11 C
 12 C++
 13 C#
 14 Clojure
 15 CMake
 16 Common Lisp
 17 D
 18 Déjà Vu
 19 Delphi
 20 DWScript
 21 EchoLisp
 22 Elena
 23 Elixir
 24 Erlang
 25 Euler Math Toolbox
 26 Factor
 27 Fortran
 28 FreeBASIC
 29 Free Pascal
 30 FutureBasic
 31 GAP
 32 Go
 33 Golfscript
 34 Groovy
 35 Haskell
 36 Icon and Unicon
 37 Io
 38 Inform 7
 39 J
 40 Java
 41 JavaScript
 42 Julia
 43 Kotlin
 44 Lua
 45 Mathematica
 46 MATLAB
 47 Maxima
 48 Modula3
 49 Nemerle
 50 NetRexx
 51 Nim
 52 OCaml
 53 Octave
 54 Oz
 55 PARI/GP
 56 Pascal
 57 Perl
 58 Perl 6
 59 Phix
 60 PHP
 61 PicoLisp
 62 PL/I
 63 PL/SQL
 64 PowerShell
 65 PureBasic
 66 Python
 67 R
 68 Racket
 69 Rascal
 70 REXX
 71 Ring
 72 Ruby
 73 Run BASIC
 74 Rust
 75 Scala
 76 Seed7
 77 Sidef
 78 Sparkling
 79 Stata
 80 Tcl
 81 TI83 BASIC
 82 TXR
 83 UNIX Shell
 84 Ursa
 85 Ursala
 86 XPL0
 87 zkl
 88 ZX Spectrum Basic
8th[edit]
The default random number generator in 8th is a cryptographically strong one using Fortuna, which is seeded from the system's entropy provider. An additional random generator (which is considerably faster) is a PCG, though it is not cryptographically strong.
ActionScript[edit]
In both Actionscript 2 and 3, the type of pseudorandom number generator is implementationdefined. 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[edit]
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 pseudorandom 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."
 Ada 95 RM  A.5.2 Random Number Generation
 Ada 2005 RM  A.5.2 Random Number Generation
 Ada 2005 RM  A.5.2 Random Number Generation
ALGOL 68[edit]
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
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a :=
¢ the next pseudorandom ℒ 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 pseudorandomness
and uniform distribution of the sequence of integral values ¢);
INT ℒ last random := # some initial random number #;
PROC ℒ random = ℒ REAL: ℒ next random(ℒ last random);
Note the suitable "next random number" is suggested to be: ( a := ¢ the next pseudorandom ℒ 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 pseudorandomness 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:
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);
AutoHotkey[edit]
The builtin command Random generates a pseudorandom number using Mersenne Twister "MT19937" (see documentation).
AWK[edit]
The builtin command "rand" generates a pseudorandom uniform distributed random variable. More information is available from the documentation of gawk.
It is important that the RNG is seeded with the funtions "srand", otherwise, the same random number is produced.
Example usage: see #UNIX_Shell
BASIC[edit]
The RND function generates a pseudo random number greater than or equal to zero, but less than one. The implementation is machine specific based on contents of the ROM and there is no fixed algorithm.
Batch File[edit]
Windows batch files can use the %RANDOM%
pseudovariable which returns a pseudorandom 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:
BBC BASIC[edit]
The RND function uses a 33bit maximallength Linear Feedback Shift Register (LFSR), with 32bits being used to provide the result. Hence the sequence length is 2^331, during which the value zero is returned once and all nonzero 32bit values are each returned twice.
Befunge[edit]
The ? instruction usually uses the random number generator in the interpreter's language. The original interpreter is written in C and uses rand().
C[edit]
Standard C has rand(). Some implementations of C have other sources of random numbers, along with rand().
C rand()[edit]
The C standard specifies the interface to the rand() and srand() functions in <stdlib.h>.

void srand(unsigned int seed)
begins a new sequence of pseudorandom integers. 
int rand(void)
returns a pseudorandom integer in the range from 0 to RAND_MAX. RAND_MAX must be at least 32767.
The same seed to srand() reproduces the same sequence. The default seed is 1, when a program calls rand() without calling srand(); so srand(1) reproduces the default sequence. (n1124.pdf)
There are no requirements as to the algorithm to be used for generating the random numbers. All versions of rand() return integers that are uniformly distributed in the interval from 0 to RAND_MAX, but some algorithms have problems in their randomness. For example, the cycle might be too short, or the probabilities might not be independent.
Many popular C libraries implement rand() 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. These rand() functions should not be used where a good quality random number generator is required.
BSD rand()[edit]
Among current systems, BSD might have the worst algorithm for rand(). BSD rand() sets RAND_MAX to and uses this linear congruential formula:
FreeBSD switched to a different formula, but NetBSD and OpenBSD stayed with this formula. (NetBSD rand.c, OpenBSD rand.c)
BSD rand() produces a cycling sequence of only possible states; this is already too short to produce good random numbers. The big problem with BSD rand() is that the low bits' cycle sequence length is only . (This problem happens because the modulus is a power of two.) The worst case, when , becomes obvious if one uses the low bit to flip a coin.
#include <stdio.h>
#include <stdlib.h>
/* Flip a coin, 10 times. */
int
main()
{
int i;
srand(time(NULL));
for (i = 0; i < 10; i++)
puts((rand() % 2) ? "heads" : "tails");
return 0;
}
If the C compiler uses BSD rand(), then this program has only two possible outputs.
 At even seconds: heads, tails, heads, tails, heads, tails, heads, tails, heads, tails.
 At odd seconds: tails, heads, tails, heads, tails, heads, tails, heads, tails, heads.
The low bit manages a uniform distribution between heads and tails, but it has a period length of only 2: it can only flip a coin 2 times before it must repeat itself. Therefore it must alternate heads and tails. This is not a real coin, and these are not truly random flips.
In general, the low bits from BSD rand() are much less random than the high bits. This defect of BSD rand() is so famous that some programs ignore the low bits from rand().
Microsoft rand()[edit]
Microsoft sets RAND_MAX to 32767 and uses this linear congruential formula:
POSIX drand48()[edit]
POSIX adds the drand48() family to <stdlib.h>.

void srand48(long seed)
begins a new sequence. 
double drand48(void)
returns a random double in [0.0, 1.0). 
long lrand48(void)
returns a random long in [0, 2**31). 
long mrand48(void)
returns a random long in [2**31, 2**31).
This family uses a 48bit linear congruential generator with this formula:
C++[edit]
As part of the C++11 specification the language now includes various forms of random number generation.
While the default engine is implementation specific (ex, unspecified), the following Pseudorandom generators are available in the standard:
 Linear congruential (minstd_rand0, minstd_rand)
 Mersenne twister (mt19937, mt19937_64)
 Subtract with carry (ranlux24_base, ranlux48_base)
 Discard block (ranlux24, ranlux48)
 Shuffle order (knuth_b)
Additionally, the following distributions are supported:
 Uniform distributions: uniform_int_distribution, uniform_real_distribution
 Bernoulli distributions: bernoulli_distribution, geometric_distribution, binomial_distribution, negative_binomial_distribution
 Poisson distributions: poisson_distribution, gamma_distribution, exponential_distribution, weibull_distribution, extreme_value_distribution
 Normal distributions: normal_distribution, fisher_f_distribution, cauchy_distribution, lognormal_distribution, chi_squared_distribution, student_t_distribution
 Sampling distributions: discrete_distribution, piecewise_linear_distribution, piecewise_constant_distribution
Example of use:
#include <iostream>
#include <string>
#include <random>
int main()
{
std::random_device rd;
std::uniform_int_distribution<int> dist(1, 10);
std::mt19937 mt(rd());
std::cout << "Random Number (hardware): " << dist(rd) << std::endl;
std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl;
}
C#[edit]
The .NET Random class says that it uses Knuth's subtractive random number generator algorithm.[4]
Clojure[edit]
See Java.
CMake[edit]
CMake has a random string generator.
# Show random integer from 0 to 9999.
string(RANDOM LENGTH 4 ALPHABET 0123456789 number)
math(EXPR number "${number} + 0") # Remove extra leading 0s.
message(STATUS ${number})
The current implementation (in cmStringCommand.cxx and cmSystemTools.cxx) calls rand() and srand() from C. It picks random letters from the alphabet. The probability of each letter is near 1 ÷ length, but the implementation uses floatingpoint arithmetic to map RAND_MAX + 1 values onto length letters, so there is a small modulo bias when RAND_MAX + 1 is not a multiple of length.
CMake 2.6.x has bug #9851; two random strings might be equal because they use the same seed. CMake 2.8.0 fixes this bug by seeding the random generator only once, during the first call to string(RANDOM ...)
.
CMake 2.8.5 tries a secure seed (CryptGenRandom or /dev/urandom) or falls back to highresolution system time. Older versions seed the random generator with time(NULL)
, the current time in seconds.
Common Lisp[edit]
The easiest way to generate random numbers in Common Lisp is to use the builtin rand function after seeding the random number generator. For example, the first line seeds the random number generator and the second line generates a number from 0 to 9
(setf *randomstate* (makerandomstate t))
(rand 10)
Common Lisp: The Language, 2nd Ed. does not specify a specific random number generator algorithm.
D[edit]
From std.random:
The generators feature a number of wellknown and welldocumented methods of generating random numbers. An overall fast and reliable means to generate random numbers is the Mt19937 generator, which derives its name from "Mersenne Twister with a period of 2 to the power of 19937". In memoryconstrained situations, linear 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.
Déjà Vu[edit]
The standard implementation, vu
, uses a Mersenne twister.
!print randomint # prints a 32bit random integer
Delphi[edit]
According to Wikipedia, Delphi uses a Linear Congruential Generator.
Random functions:
function Random : Extended; function Random ( LimitPlusOne : Integer ) : Integer; procedure Randomize;
DWScript[edit]
DWScript currently uses a 64bit XorShift PRNG, which is a fast and light form of GFSR.
EchoLisp[edit]
EchoLisp uses an ARC4 (or RCA4) implementation by David Bau, which replaces the JavaScript Math.random(). Thanks to him. [5]. Some examples :
(randomseed "albert")
(random) → 0.9672510261922906 ; random float in [0 ... 1[
(random 1000) → 726 ; random integer in [0 ... 1000 [
(random 1000) → 936 ; random integer in ]1000 1000[
(lib 'bigint)
(random 1e200) → 48635656441292641677...3917639734865662239925...9490799697903133046309616766848265781368
Elena[edit]
ELENA 3.2 :
import extensions.
program =
[
console printLine(randomGenerator nextReal).
console printLine(randomGenerator eval(0,100)).
].
 Output:
0.706398 46
Elixir[edit]
Elixir does not come with its own module for random number generation. But you can use the appropriate Erlang functions instead. Some examples:
# Seed the RNG
:random.seed(:erlang.now())
# Integer in the range 1..10
:random.uniform(10)
# Float between 0.0 and 1.0
:random.uniform()
For further information, read the Erlang section.
Erlang[edit]
Random number generator. The method is attributed to B.A. Wichmann and I.D.Hill, in 'An efficient and portable pseudorandom number generator', Journal of Applied Statistics. AS183. 1982. Also Byte March 1987.
The current algorithm is a modification of the version attributed to Richard A O'Keefe in the standard Prolog library.
Every time a random number is requested, a state is used to calculate it, and a new state produced. The state can either be implicit (kept in the process dictionary) or be an explicit argument and return value. In this implementation, the state (the type ran()) consists of a tuple of three integers.
It should be noted that this random number generator is not cryptographically strong. If a strong cryptographic random number generator is needed for example crypto:rand_bytes/1 could be used instead.
Seed with a fixed known value triplet A1, A2, A3:
random:seed(A1, A2, A3)
Example with the running time:
...
{A1,A2,A3} = erlang:now(),
random:seed(A1, A2, A3),
...sequence of randoms used
random:seed(A1, A2, A3),
...same sequence of randoms used
Get a random float value between 0.0 and 1.0:
Rfloat = random:uniform(),
Get a random integer value between 1 and N (N is an integer >= 1):
Rint = random:uniform(N),
Euler Math Toolbox[edit]
Bays and Durham as describend in Knuth's book.
Factor[edit]
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]
Fortran[edit]
Fortran has intrinsic random_seed() and random_number() subroutines. Used algorithm of the pseudorandom number generator is compiler dependent (not specified in ISO Fortran Standard, see ISO/IEC 15391:2010 (E), 13.7.135 RANDOM NUMBER). For algorithm in GNU gfortran see https://gcc.gnu.org/onlinedocs/gfortran/RANDOM_005fNUMBER.html Note that with the GNU gfortran compiler program needs to call random_seed with a random PUT= argument to get a pseudorandom number otherwise the sequence always starts with the same number. Intel compiler ifort reinitializes the seed randomly without PUT argument to random value using the system date and time. Here we are seeding random_seed() with some number obtained from the Linux urandom device.
program rosetta_random
implicit none
integer, parameter :: rdp = kind(1.d0)
real(rdp) :: num
integer, allocatable :: seed(:)
integer :: un,n, istat
call random_seed(size = n)
allocate(seed(n))
! Seed with the OS random number generator
open(newunit=un, file="/dev/urandom", access="stream", &
form="unformatted", action="read", status="old", iostat=istat)
if (istat == 0) then
read(un) seed
close(un)
end if
call random_seed (put=seed)
call random_number(num)
write(*,'(E24.16)') num
end program rosetta_random
FreeBASIC[edit]
FreeBASIC has a Rnd() function which produces a pseudorandom double precision floating point number in the halfclosed interval [0, 1) which can then be easily used to generate pseudorandom numbers (integral or decimal) within any range.
The sequence of pseudorandom numbers can either by seeded by a parameter to the Rnd function itself or to the Randomize statement and, if omitted, uses a seed based on the system timer.
However, a second parameter to the Randomize statement determines which of 5 different algorithms is used to generate the pseudorandom numbers:
1. Uses the C runtime library's rand() function (based on LCG) which differs depending on the platform but produces a low degree of randomness.
2. Uses a fast, platform independent, algorithm with 32 bit granularity and a reasonable degree of randomness. The basis of this algorithm is not specified in the language documentation.
3. Uses the Mersenne Twister algorithm (based on GFSR) which is platform independent, with 32 bit granularity and a high degree of randomness. This is good enough for most noncryptographic purposes.
4. Uses a QBASIC compatible algorithm which is platform independent, with 24 bit granularity and a low degree of randomness.
5. Uses system features (Win32 Crypto API or /dev/urandom device on Linux) to generate pseudorandom numbers, with 32 bit granularity and a very high degree of randomness (cryptographic strength).
A parameter of 0 can also be used (and is the default if omitted) which uses algorithm 3 in the lang fb dialect, 4 in the lang qb dialect and 1 in the lang fblite dialect.
Free Pascal[edit]
FreePascal's function random uses the MersenneTwister (for further details, see the file rtl/inc/system.inc).
FutureBasic[edit]
Syntax:
randomInteger = rnd(expr)
This function returns a pseudorandom long integer uniformly distributed in the range 1 through expr. The expr parameter should be greater than 1, and must not exceed 65536. If the value returned is to be assigned to a 16bit integer (randomInteger), expr should not exceed 32767. The actual sequence of numbers returned by rnd depends on the random number generator's "seed" value. (Note that rnd(1) always returns the value 1.)
Syntax:
random (or randomize) [expr]
This statement "seeds" the random number generator: this affects the sequence of values which are subsequently returned by the rnd function and the maybe function. The numbers returned by rnd and maybe are not truly random, but follow a "pseudorandom" sequence which is uniquely determined by the seed number (expr). If you use the same seed number on two different occasions, you'll get the same sequence of "random" numbers both times. When you execute random without any expr parameter, the system's current time is used to seed the random number generator.
Example 1:
random 375 // using seed number
Example 2:
random // current system time used as seed
Example: To get a random integer between two arbitrary limits min and max, use the following statement. (Note: max  min must be less than or equal to 65536.):
randomInteger = rnd(max  min + 1) + min  1
To get a random fraction, greater than or equal to zero and less than 1, use this statement:
frac! = (rnd(65536)1)/65536.0
To get a random long integer in the range 1 through 2,147,483,647, use this statement:
randomInteger& = ((rnd(65536)  1)<<15) + rnd(32767)
GAP[edit]
GAP may use 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).
# 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);
One can get random elements from many objects, including lists
Random([1, 10, 100]);
# Random permutation of 1..200
Random(SymmetricGroup(200));
# Random element of Z/23Z :
Random(Integers mod 23);
Go[edit]
Go has two packages providing random numbers.
 math/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 Unixlike systems and the CryptGenRandom API on Windows.
Golfscript[edit]
Golfscript uses Ruby's Mersenne Twister algorithm
~rand
produces a random integer between 0 and n1, where n is a positive integer piped into the program
Groovy[edit]
Same as Java.
Haskell[edit]
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[edit]
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 builtin values.Io[edit]
Io's Random object uses the Mersenne Twister algorithm.
Inform 7[edit]
Inform's random functions are built on the random number generator exposed at runtime by the virtual machine, which is implementationdefined.
J[edit]
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[edit]
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.
JavaScript[edit]
The only builtin random number generation facility is Math.random()
, which returns a floatingpoint number greater than or equal to 0 and less than 1, with approximately uniform distribution. The standard (ECMA262) does not specify what algorithm is to be used.
Julia[edit]
Julia's builtin randomnumber generation functions, rand()
etcetera, use the Mersenne Twister algorithm.
Kotlin[edit]
As mentioned in the Java entry, the java.util.Random class uses a linear congruential formula and is not therefore cryptographically secure. However, there is also a derived class, java.security.SecureRandom, which can be used for cryptographic purposes
Lua[edit]
Lua's math.random()
is an interface to the C rand()
function provided by the OS libc; its implementation varies by platform.
Mathematica[edit]
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[edit]
MATLAB uses the Mersenne Twister as its default random number generator. Information about how the "rand()" function is utilized is given at MathWorks.
Maxima[edit]
Maxima uses a Lisp implementation of the Mersenne Twister. See ? random
for help, or file share/maxima/5.28.02/src/randmt19937.lisp
for the source code.
There are also random generators for several distributions in package distrib
:

random_bernoulli

random_beta

random_binomial

random_cauchy

random_chi2

random_continuous_uniform

random_discrete_uniform

random_exp

random_f

random_gamma

random_general_finite_discrete

random_geometric

random_gumbel

random_hypergeometric

random_laplace

random_logistic

random_lognormal

random_negative_binomial

random_noncentral_chi2

random_noncentral_student_t

random_normal

random_pareto

random_poisson

random_rayleigh

random_student_t

random_weibull
Note: the package distrib
also has functions starting with pdf
, cdf
, quantile
, mean
, var
, std
, skewness
or kurtosis
instead of random
, except the Cauchy distribution, which does not have moments.
Modula3[edit]
The Random interface in Modula3 states that it uses "an additive generator based on Knuth's Algorithm 3.2.2A".
Nemerle[edit]
Uses .Net Random class; so, as mentioned under C#, above, implements Knuth's subtractive random number generator algorithm. Random class documentation at MSDN.
NetRexx[edit]
As NetRexx runs in the JVM it simply leverages the Java library. See Java for details of the algorithms used.
Nim[edit]
There are two PRNGs provided in the standard library:
 random : Based on xoroshiro128+ (xor/rotate/shift/rotate), see here.
 mersenne : The Mersenne Twister.
OCaml[edit]
OCaml provides a module called Random in its standard library. It used to be a "Linear feedback shift register" pseudorandom number generator (References: Robert Sedgewick, "Algorithms", AddisonWesley). It is now (as of version 3.12.0) a "laggedFibonacci F(55, 24, +) with a modified addition function to enhance the mixing of bits." It passes the Diehard test suite.
Octave[edit]
As explained here (see rand function), Octave uses the "Mersenne Twister with a period of 2^199371".
Oz[edit]
Oz provides a binding to the C rand
function as OS.rand
.
PARI/GP[edit]
random
uses Richard Brent's xorgens. It's a member of the xorshift class of PRNGs and provides good, fast pseudorandomness (passing the BigCrush test, unlike the Mersenne twister), but it is not cryptographically strong. As implemented in PARI, its period is "at least ".
setrand(3)
random(6)+1
\\ chosen by fair dice roll.
\\ guaranteed to the random.
Pascal[edit]
See #Delphi and #Free Pascal.
Random functions:
function Random(l: LongInt) : LongInt; function Random : Real; procedure Randomize;
Perl[edit]
Previous to Perl 5.20.0 (May 2014), Perl's rand
function will try and call drand48
, random
or rand
from the C library stdlib.h
in that order.
Beginning with Perl 5.20.0, a drand48() implementation is built into Perl and used on all platforms. The implementation is from FreeBSD and uses a 48bit linear congruential generator with this formula:
Seeds for drand48 are 32bit and the initial seed uses 4 bytes of data read from /dev/urandom if possible; a 32bit mix of various system values otherwise.
Additionally, there are many PRNG's available as modules. Two good Mersenne Twister modules are Math::Random::MTwist and Math::Random::MT::Auto. Modules supporting other distributions can be found in Math::Random and Math::GSL::Randist among others. CSPRNGs include Bytes::Random::Secure, Math::Random::Secure, Math::Random::ISAAC, and many more.
Perl 6[edit]
The implementation underlying the rand function is platform and VM dependent. The JVM backend uses that platform's SecureRandom class.
Phix[edit]
The rand(n) routine returns an integer in the range 1 to n, and rnd() returns a floating point number between 0.0 and 1.0.
In both cases the underlying algorithm is just about as trivial as it can be, certainly not suitable for serious cryptographic work.
There are at least a couple of Mersenne twister components in the archive.
PHP[edit]
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[edit]
PicoLisp uses a linear congruential generator in the builtin (rand) function, with a multiplier suggested in Knuth's "Seminumerical Algorithms". See the documentation.
PL/I[edit]
Values produced by IBM Visualage PL/I compiler builtin random number generator are uniformly distributed between 0 and 1 [0 <= random < 1]
It uses a multiplicative congruential method:
seed(x) = mod(950706376 * seed(x1), 2147483647)
random(x) = seed(x) / 2147483647
PL/SQL[edit]
Oracle Database has two packages that can be used for random numbers generation.
DBMS_RANDOM[edit]
The DBMS_RANDOM package provides a builtin random number generator. This package is not intended for cryptography. It will automatically initialize with the date, user ID, and process ID if no explicit initialization is performed. If this package is seeded twice with the same seed, then accessed in the same way, it will produce the same results in both cases.
DBMS_RANDOM.RANDOM produces integers in [2^^31, 2^^31).
DBMS_RANDOM.VALUE produces numbers in [0,1) with 38 digits of precision.
DBMS_RANDOM.NORMAL produces normal distributed numbers with a mean of 0 and a variance of 1
DBMS_CRYPTO[edit]
The DBMS_CRYPTO package contains basic cryptographic functions and procedures. The DBMS_CRYPTO.RANDOMBYTES function returns a RAW value containing a cryptographically secure pseudorandom sequence of bytes, which can be used to generate random material for encryption keys. This function is based on the RSA X9.31 PRNG (PseudoRandom Number Generator).
DBMS_CRYPTO.RANDOMBYTES returns RAW value
DBMS_CRYPTO.RANDOMINTEGER produces integers in the BINARY_INTEGER datatype
DBMS_CRYPTO.RANDOMNUMBER produces integer in the NUMBER datatype in the range of [0..2**1281]
PowerShell[edit]
The GetRandom
cmdlet (part of PowerShell 2) uses the .NETsupplied pseudorandom number generator which uses Knuth's subtractive method; see C#.
PureBasic[edit]
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[edit]
Python uses the Mersenne twister algorithm accessed via the builtin random module.
R[edit]
For uniform random numbers, R may use WichmannHill, Marsagliamulticarry, SuperDuper, MersenneTwister, or KnuthTAOCP (both 1997 and 2002 versions), or a userdefined method. The default is Mersenne Twister.
R is able to generate random numbers from a variety of distributions, e.g.
 Beta
 Binomial
 Cauchy
 ChiSquared
 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
?RNG
help.search("Distribution", package="stats")
Racket[edit]
Racket's random number generator uses a 54bit version of L’Ecuyer’s MRG32k3a algorithm [L'Ecuyer02], as specified in the docs. In addition, the "math" library has a bunch of additional random functions.
Rascal[edit]
Rascal does not have its own arbitrary number generator, but uses the Java generator. Nonetheless, you can redefine the arbitrary number generator if needed. Rascal has the following functions connected to the random number generator:
import util::Math;
arbInt(int limit); // generates an arbitrary integer below limit
arbRat(int limit, int limit); // generates an arbitrary rational number between the limits
arbReal(); // generates an arbitrary real value in the interval [0.0, 1.0]
arbSeed(int seed);
The last function can be used to redefine the arbitrary number generator. This function is also used in the getOneFrom() functions.
rascal>import List;
ok
rascal>getOneFrom(["zebra", "elephant", "snake", "owl"]);
str: "owl"
REXX[edit]
The RANDOM BIF function is a pseudorandom number (nonnegative integer) generator,
with a range (spread) limited to 100,000 (but some REXX interpreters support a larger range).
The random numbers generated are not consistent between different REXX interpreters or
even the same REXX interpreters executing on different hardware.
/*(below) returns a random integer between 100 & 200, inclusive.*/
y = random(100, 200)
The random numbers may be repeatable by specifiying a seed for the random BIF:
call random ,,44 /*the seed in this case is "44". */
.
.
.
y = random(100, 200)
Comparison of random BIF output for different REXX implementations using a deterministic seed.
/* REXX ***************************************************************
* 08.09.2013 Walter Pachl
* Please add the output from other REXXes
* 10.09.2013 Walter Pachl added REXX/TSO
* 01.08.2014 Walter Pachl show what ooRexx supports
**********************************************************************/
Parse Version v
Call random ,,44
ol=v':'
Do i=1 To 10
ol=ol random(1,10)
End
If left(v,11)='REXXooRexx' Then
ol=ol random(999999999,0) /* ooRexx supports negative limits */
Say ol
outputs from various REXX interpreters:
REXXooRexx_4.1.3(MT) 6.03 4 Jul 2013: 3 10 6 8 6 9 9 1 1 6 REXXooRexx_4.2.0(MT)_32bit 6.04 22 Feb 2014: 3 10 6 8 6 9 9 1 1 6 403019526 REXX/Personal 4.00 21 Mar 1992: 7 7 6 7 8 8 5 9 4 7 REXXr4 4.00 17 Aug 2013: 8 10 7 5 4 2 10 5 2 4 REXXroo 4.00 28 Jan 2007: 8 10 7 5 4 2 10 5 2 4 REXXRegina_3.7(MT) 5.00 14 Oct 2012: 10 2 7 10 1 1 8 2 4 1 are the following necessary?? REXXRegina_3.4p1 (temp bug fix sf.org 1898218)(MT) 5.00 21 Feb 2008: 10 2 7 10 1 1 8 2 4 1 REXXRegina_3.2(MT) 5.00 25 Apr 2003: 10 2 7 10 1 1 8 2 4 1 REXXRegina_3.3(MT) 5.00 25 Apr 2004: 10 2 7 10 1 1 8 2 4 1 REXXRegina_3.4(MT) 5.00 30 Dec 2007: 10 2 7 10 1 1 8 2 4 1 REXXRegina_3.5(MT) 5.00 31 Dec 2009: 10 2 7 10 1 1 8 2 4 1 REXXRegina_3.6(MT) 5.00 31 Dec 2011: 10 2 7 10 1 1 8 2 4 1 REXX370 3.48 01 May 1992: 8 7 3 1 6 5 5 8 3 2
Conclusion: It's not safe to transport a program that uses 'reproducable' use of randombif (i.e. with a seed) from one environment/implementation to another :(
Ring[edit]
nr = 10
for i = 1 to nr
see random(i) + nl
next
Ruby[edit]
Ruby's rand
function currently uses the Mersenne twister algorithm, as described in its documentation.
Run BASIC[edit]
rmd(0) Return a pseudorandom value between 0 and 1
Rust[edit]
Rust's rand
crate offers several PRNGs. (It is also available via #![feature(rustc_private)]
). The offering includes some cryptographically secure PRNGs: ISAAC (both 32 and 64bit variants) and ChaCha20. StdRng
is a wrapper of one of those efficient on the current platform. The crate also provides a weak PRNG: Xorshift128. It passes diehard but fails TestU01, replacement is being considered. thread_rng
returns a thread local StdRng
initialized from the OS. Other PRNGs can be created from the OS or with thread_rng
.
For any other PRNGs not provided, they merely have to implement the Rng
trait.
Scala[edit]
Scala's scala.util.Random
class uses a Linear congruential formula of the JVM runtime libary, as described in its documentation.
An example can be found here:
import scala.util.Random
/**
* Histogram of 200 throws with two dices.
*/
object Throws extends App {
Stream.continually(Random.nextInt(6) + Random.nextInt(6) + 2)
.take(200).groupBy(identity).toList.sortBy(_._1)
.foreach {
case (a, b) => println(f"$a%2d:" + "X" * b.size)
}
}
 Output:
2:XXX 3:XXXXXXXXX 4:XXXXXXXXXXXXX 5:XXXXXXXXXXXXXXXXXXXXXXXXXX 6:XXXXXXXXXXXXXXXXXXXXXXXXXXXXX 7:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 8:XXXXXXXXXXXXXXXXXXXXXXXXXXXX 9:XXXXXXXXXXXXXXXXXXXXXXXXXXXX 10:XXXXXXXXXXXXXXXXX 11:XXXXXXXXXXXXXX 12:XX
Seed7[edit]
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.
Sidef[edit]
Latest versions of Sidef use the Mersenne Twister algorithm to compute pseudorandom numbers, with different initial seeds (and implementations) for floatingpoints and integers.
say 1.rand # random float in the interval [0,1)
say 100.irand # random integer in the interval [0,100)
Sparkling[edit]
Sparkling uses the builtin PRNG of whichever C library implementation the interpreter is compiled against. The Sparkling library functions random() and seed() map directly to the C standard library functions rand() and srand() with only one small difference: the return value of rand() is divided by RAND_MAX so that the generated number is between 0 and 1.
Stata[edit]
See set rng in Stata help. Stata uses the Mersenne Twister RNG by default, and may use the 32bit KISS RNG for compatibility with versions earlier than Stata 14.
Tcl[edit]
Tcl uses a linear congruential generator in it's builtin rand()
function. This is seeded by default from the system time, and kept perinterpreter 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):11921201, Oct 1988
 W.H. Press & S.A. Teukolsky, “Portable random number generators,” Computers in Physics 6(5):522524, Sep/Oct 1992.
TI83 BASIC[edit]
TI83 uses L'Ecuyer's algorithm to generate random numbers. See L'Ecuyer's algorithm. More explainations can be found in this paper.
Random function:
rand
TXR[edit]
TXR 50 has a PRNG API, and uses a reimplementation of WELL 512 (avoiding contagion by the "contact authors for commercial uses" virus present in the reference implementation, which attacks BSD licenses). Mersenne Twister was a runner up. There is an object of type randomstate, and a global variable *randomstate* which holds the default random state. Programs can create random states which are snapshots of existing ones, or which are seeded using an integer value (which can be a bignum). The random function produces a random number modulo some integer value, which can have arbitrary precision. The randomfixnum function produces a nonheapallocated positive integer with random bits.
UNIX Shell[edit]
All Bourne Shell clones have a very quick pseudo random number generator.
echo $RANDOM
Rach time $RANDOM is referenced it changes it's value (with it's maximum value 32767).
Ursa[edit]
Standard Ursa defines the ursa.util.random
type for random number generators and gives objects of this type a standard interface, but leaves the choice of algorithm up to the implementor.
Cygnus/X Ursa is written in Java and makes calls to java.util.Random, which uses a Linear congruential formula.
Ursala[edit]
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.
XPL0[edit]
A 31bit linear congruential generator is used based on an algorithm by Donald Knuth in his book "Art of Computer Programming" Vol 2, 3rd ed. p. 185. It passes all tests in the Diehard suite. The seed is initialized with the system timer count (at 046C) whenever a program starts. The seed can also be set within a program to give a repeatable sequence of (pseudo) random numbers. Calls to the random number intrinsic return values modulo the argument.
include c:\cxpl\codes; \intrinsic 'code' declarations
int I;
[RanSeed(12345); \set random number generator seed to 12345
for I:= 1 to 5 do
[IntOut(0, Ran(1_000_000)); CrLf(0)];
]
Output:
905495 181227 755989 244883 213142
zkl[edit]
zkl uses the Xorshift (http://en.wikipedia.org/wiki/Xorshift) random number generator. It will also, on occasion, read from /dev/urandom.
ZX Spectrum Basic[edit]
The ZX Spectrum uses a pseudorandom number generator that derives its numbers from a set of values stored in the system ROM. The random numbers produced will repeat after 65535 iterations.
 Programming Tasks
 Solutions by Programming Task
 8th
 ActionScript
 Ada
 ALGOL 68
 AutoHotkey
 AWK
 BASIC
 Batch File
 BBC BASIC
 Befunge
 C
 C++
 C sharp
 Clojure
 CMake
 Common Lisp
 D
 Déjà Vu
 Delphi
 DWScript
 EchoLisp
 Elena
 Elixir
 Erlang
 Euler Math Toolbox
 Factor
 Fortran
 FreeBASIC
 Free Pascal
 FutureBasic
 GAP
 Go
 Golfscript
 Groovy
 Haskell
 Icon
 Unicon
 Icon Programming Library
 Io
 Inform 7
 J
 Java
 JavaScript
 Julia
 Kotlin
 Lua
 Mathematica
 MATLAB
 Maxima
 Modula3
 Nemerle
 NetRexx
 Nim
 OCaml
 Octave
 Oz
 PARI/GP
 Pascal
 Perl
 Perl 6
 Phix
 PHP
 PicoLisp
 PL/I
 PL/SQL
 PowerShell
 PureBasic
 Python
 R
 Racket
 Rascal
 REXX
 Ring
 Ruby
 Run BASIC
 Rust
 Scala
 Seed7
 Sidef
 Sparkling
 Stata
 Tcl
 TI83 BASIC
 TXR
 UNIX Shell
 Ursa
 Ursala
 XPL0
 Zkl
 ZX Spectrum Basic
 Bc/Omit
 Dc/Omit
 GUISS/Omit
 Sed/Omit
 Unlambda/Omit
 Randomness