How do we code Randomness ?
- Generates random numbers from a physical process capable of producing entropy (in other words, the device always has access to a physical entropy source)
- Nature provides ample phenomena that generate low-level, statistically random "noise" signals, including thermal and shot noise, jitter and metastability of electronic circuits, Brownian motion, atmospheric noise, radioactive decay.
- Services/Devices: USBs, Quantum RNGs, Free Running Oscillators (FROs)
- Utilizes a deterministic algorithm to generate a sequence of numbers whose properties approximate the properties of sequences of random numbers.
- The PRNG-generated sequence is not truly random, because it is completely determined by an initial value, called the PRNG's seed (which may include truly random values).
- Important in practice for their speed in number generation and their reproducibility.
The generator is defined by the recurrence relation:
a is "multiplier"
c is "increment"
X0 is "seed" value
Implementation | modulus: m | increment: c | multiplier: a |
---|---|---|---|
C++ 11's minstd_rand | 231-1 | 48271 | 0 |
Java's java.util.Random | 248 | 25214903917 | 11 |
From Javascript's v8 engine official source code:
static inline void XorShift128(uint64_t* state0, uint64_t* state1) {
uint64_t s1 = *state0;
uint64_t s0 = *state1;
*state0 = s0;
s1 ^= s1 << 23;
s1 ^= s1 >> 17;
s1 ^= s0;
s1 ^= s0 >> 26;
*state1 = s1;
}
- Javascript
- Math.Random() implementation depends on engine (browser).
- v8 engine uses xorshift128+
- Python
- CPython uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1.
- Java
- Uses a modified linear congruential formula.
public synchronized void setSeed(long seed) { this.seed = (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1); haveNextNextGaussian = false; } protected synchronized int next(int bits) { seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1); return (int) (seed >>> (48 - bits)); }
- C++
RNGs can be tested against statistical test suites: