3. Random Number Generation
Every random variate in a simulation is built from i.i.d. U(0,1) numbers; these notes cover where those numbers come from and what makes a generator good.
Motivation. Consider simulating an queue (Markovian, i.e. exponential, interarrival times; exponential service times; one server). We must repeatedly generate , whose c.d.f. is , . This can be done from a single uniform random number:
- Generate .
- Return .
Why it works: setting and solving for gives ; since as well, we may use instead. Then
The same idea applies to other distributions: every random variate in a simulation is built from i.i.d. numbers.
Goal of this chapter. Produce a sequence of i.i.d. random numbers, i.e. numbers with p.d.f.
Three alternative sources of “random” numbers
1. True random numbers (from physical experiments)
- Draw numbered balls from an urn.
- Electrical circuits: a hardware random number machine, e.g. ERNIE (Electronic Random Number Indicator Equipment).
- Disadvantages:
- Not reproducible. Reproducibility matters in simulation: it makes debugging easier, and it gives sharper comparisons when two alternative systems are run on the same random inputs.
- Difficult to implement.
- Slow.
2. Pseudo-random numbers — a completely deterministic sequence that is statistically indistinguishable from a true random sequence. This is what simulation uses in practice, and what the rest of the chapter is about.
3. Quasi-random numbers (used in Monte Carlo integration rather than in simulation)
An integral over is an expectation under , because the p.d.f. equals there:
So generate and estimate the integral by
By the CLT the error of this estimator is of order . The idea of quasi-random numbers is to replace the random sequence by a deterministic sequence that covers more evenly; this improves the error rate to order . Such sequences are not i.i.d., so they are useless as simulation inputs, but for integration the even coverage is exactly what helps.
3.1. Random Number Generators (RNGs)
Desired properties of an RNG
- Uniformity: the sequence should appear to be uniformly distributed on .
- Independence: terms in the sequence should not be correlated.
- Reproducibility: one must be able to reproduce a particular stream of random numbers (e.g. from a seed).
- Fast, with low memory usage.
- Long period. A deterministic generator eventually loops. The segment of non-repeating numbers is called a cycle, and its length is the period of the RNG.
flowchart LR
u1(("u₁")) --> u2(("u₂")) --> u3(("u₃")) --> d[". . ."] --> uP(("u_P")) --> u1
The sequence repeats after terms, so the period must be far longer than the number of random numbers a simulation will consume.
3.2. Linear Congruential Generators (LCGs)
An LCG produces integers by the recursion
where is the initial seed, is the multiplier, is the increment, and is the modulus. All four are non-negative integers, and is the remainder when is divided by .
3.2.1. From integers to uniforms.
Since is a remainder after division by ,
Dividing by scales these into the unit interval:
The are the “random numbers” delivered to the simulation; the are the generator’s internal state.
Example. Take , , , :
| 0 | 1 | 2 | 3 | 4 | 16 | ||
|---|---|---|---|---|---|---|---|
| 7 | 6 | 1 | 8 | 11 | 7 | ||
| 0.4375 | 0.375 | 0.0625 | 0.5 | 0.6875 | 0.4375 |
e.g. . Here , so the sequence has period .
Observations.
- Values on a grid. The can only take the values : rational numbers on an equally spaced grid, not a genuinely continuous variable. In practice one takes large, typically ; then the grid is so fine that for all practical purposes.
- Looping behaviour. Since depends only on , as soon as some earlier value reappears the whole sequence after it repeats. There are only possible values, so a value must recur within steps. The length of the repeating segment is the period of the LCG, and by this argument the period is at most . An LCG whose period equals is called a full-period LCG: it visits every value exactly once per cycle.
- Determinism. The whole sequence is fixed by . Unrolling the recursion gives the closed form (for )
so can be computed directly from the seed without generating .
Example. , , , , so :
| 0 | 1 | 2 | 3 | 4 | 16 | 17 | ||
|---|---|---|---|---|---|---|---|---|
| 7 | 6 | 1 | 8 | 11 | 7 | 6 | ||
| 0.438 | 0.375 | 0.063 | 0.5 | 0.688 | 0.438 | 0.375 |
The first repeat is , so this LCG has full period .
What if or instead? The recursion is the same, so we get the same cycle entered at a different point — e.g. — again with period . In a full-period LCG all values lie on a single cycle, so any choice of seed produces the entire cycle, in some order; the seed only picks the starting point.
For a non-full-period LCG, the values split into several cycles and the period depends on the seed:
Example. , , , so .
a. : , period .
b. : , period .
Notice that in (a) every value is a multiple of , and in (b) every value is : multiplying by never changes the power of dividing , so the sequence is trapped in its residue class. This is exactly what the theorem below rules out.
3.2.2. Necessary and sufficient conditions for a full-period LCG
Theorem (Hull–Dobell). The LCG has full period if and only if
- and are relatively prime (their only common divisor is );
- every prime that divides also divides ;
- if divides , then divides .
Why three conditions. A full-period LCG must visit every one of . The test is to look at the sequence “through a coarser lens”: for a divisor of , watch only . If the coarse sequence misses some residue mod , the full sequence misses some value mod . Condition 1 removes the obstruction coming from the increment ; condition 2 removes the obstruction coming from the multiplier , one prime at a time; condition 3 is needed because the prime misbehaves in a way no other prime does, so the lens must be checked separately.
Why each condition is necessary.
- Condition 1. Suppose and share a divisor . Modulo the recursion becomes , so if then every : the sequence never leaves the multiples of . In the example above , so and full period is impossible for any seed.
- Condition 2. Let be a prime dividing . Modulo the map is . If , then is invertible mod and the map has a fixed point . Any seed with stays in that residue class forever, so the period is less than . Hence we need , i.e. ; then the map mod is , which does cycle through all residues because by condition 1.
- Condition 3. Condition 2 with only gives odd, i.e. or . If , then applying the map twice mod gives , so the sequence mod has period at most and cannot visit all four residues. (Concretely, , , , gives ) So forces .
Sufficiency — that the three conditions together guarantee period exactly — is the harder direction and is what Hull and Dobell proved; it is not needed for the course beyond the statement.
Check on the earlier example (, , ): ; the only prime dividing is , and ; and . All three hold, so full period , as observed.
3.2.3. Two types of LCGs
Type 1: Mixed generators (LCGs with )
We want large (observation 1). The standard choice is
where is the number of bits available in a machine word. On a 32-bit system one bit is used for the sign, so and . The reason for a power of two is speed: computing costs nothing, because it is just keeping the lowest bits of (integer overflow does it automatically).
With the only prime dividing is , so the three Hull–Dobell conditions specialize as follows:
- is odd.
- is odd.
- , hence .
Item 3 implies item 2, so item 2 is redundant, but it is a common mistake to stop there: are odd yet give short periods. The rule for is therefore simply
A good mixed LCG: , , .
Check: is odd, and , so . Full period .
Type 2: Multiplicative generators (LCGs with )
- A multiplicative LCG can no longer have full period. Condition 1 of Hull–Dobell fails, since . Concretely: is a fixed point (), so the sequence can never pass through without staying there forever. A useful generator must therefore avoid altogether, and the best it can do is cycle through : the maximum possible period is .
- Period is achievable if and are chosen carefully.
- Choose prime, specifically the largest prime less than . (For this is , which happens to be prime.) Primality matters because of the next point.
- When is the period exactly ? Suppose is prime and . The sequence returns to its start at step when
Because is prime and , we can cancel , leaving
So the period is the smallest with , and it does not depend on the seed. By Fermat’s little theorem always, so this smallest divides . The period equals exactly when the smallest such is :
An with this property is called a primitive element modulo (or primitive root). Hence: if is prime and is a primitive element modulo , the multiplicative LCG has period for every seed .
Such generators — multiplicative () with a prime modulus and a primitive multiplier — are called prime modulus multiplicative LCGs (PMMLCGs). The name lists the ingredients: prime modulus is point 3, multiplicative is , and the period comes from point 4.
Example. (prime).
- : . The first with is , so is primitive and the generator has period : from it runs
- : . Here , so is not primitive; the generator splits into two cycles of length : and .
A good PMMLCG. (prime), or . Both multipliers are primitive elements modulo , so the period is .
A bad multiplicative LCG: RANDU. , , . It was the default generator on IBM mainframes in the 1960s–70s, and many early simulation papers were based on it. Its period is long enough (, the maximum for a power-of-two modulus), but it has a severe defect: because ,
and multiplying by gives the exact linear relation
So every value is determined by the two before it via a fixed formula with tiny coefficients. Geometrically, all consecutive triples lie on just parallel planes in the unit cube, instead of filling it — a gross violation of independence (property 2 of a good RNG). Any simulation that uses three successive numbers together (e.g. to generate a point in 3-D) inherits this structure.
The lesson of RANDU: a long period is necessary but not sufficient. Type 1 and Type 2 generators both need to be tested for uniformity and independence, which is the subject of the next section.
3.3. Other Kinds of Generators
More general congruential generators. Everything so far has the shape
for some function of the previous values. An LCG is the special case . Other choices of give other generators.
Multiple recursive generators (MRGs). Take linear in the last values:
where are integer constants. This is the multiplicative LCG with lags instead of one ( gives back ).
- Advantage: a huge period. The state of the generator is now the -tuple , of which there are possibilities. The all-zero tuple is a fixed point (as was for the multiplicative LCG), so the maximum period is , and this is attained for suitable when is prime. With and this is about .
- Disadvantage: multipliers to choose instead of one, and the theory for choosing them well is harder. The output sequence still looks like an LCG’s — a linear recurrence with lattice structure — just in dimensions rather than one.
Other choices of .
-
Quadratic congruential generator: , i.e.
This is nonlinear in , but it still depends on the previous value only, so the period is still at most .
-
Fibonacci generator: , i.e.
This is the MRG with and . It is very fast (no multiplication) but statistically poor. To see why, look at three consecutive outputs with . If the sum does not wrap past , then is larger than both and ; if it does wrap, is smaller than both. So is never the middle value of the three. For i.i.d. uniforms each of the six orderings of three values should occur with probability ; the Fibonacci generator produces two of them with probability .
Practical issues
- Period. The period of the RNG should be at least an order of magnitude larger than the total number of random numbers the simulation will consume. Otherwise the sequence wraps around and later parts of the run reuse the same numbers as earlier parts, destroying independence.
- Streams. A stream is a segment of the RNG’s cycle starting from a chosen seed. Use a different stream for each replication of a simulation, with the seeds spaced far enough apart that the streams do not overlap. Non-overlapping streams from one long-period generator then behave like independent generators.
flowchart LR
s1["stream 1<br/>seed z₀⁽¹⁾"] --> s2["stream 2<br/>seed z₀⁽²⁾"] --> s3["stream 3<br/>seed z₀⁽³⁾"] --> d[". . ."] --> s1
- Separate streams for separate inputs. Use different streams to simulate quantities that should be independent — e.g. one stream for interarrival times and another for service times. Besides keeping the inputs independent, this synchronizes the random numbers: when two alternative systems are simulated, each can be fed the same interarrival stream and the same service stream, so any difference in the output is due to the systems and not to the random inputs (the “sharper comparison” mentioned at the start of the chapter).
3.4. Testing RNGs
Two kinds of tests:
- Theoretical tests (number theory). These analyze the generator’s parameters mathematically and say something about the entire cycle — a global property — without generating a single . Example: the spectral test, which measures how far apart the parallel hyperplanes are on which all -tuples of an LCG lie (recall RANDU’s 15 planes).
- Empirical tests (statistics). Generate a finite sample and test the null hypothesis
These are only local tests: they examine the part of the cycle that was actually generated, so a defect elsewhere in the cycle goes undetected. has two parts, hence two families of tests: tests for uniformity and tests for independence.
3.4.1. Test for uniformity (frequency test / test)
Goal. Check whether the appear to be uniformly distributed over .
Steps.
- Divide into subintervals of equal length .
- Generate random numbers from the RNG. Rule of thumb: and (at least 5 expected observations per interval, so that the approximation in step 4 is accurate).
- Count the number of falling in the -th interval; call it , so .
- Compute the test statistic
Under each interval should receive about points, so measures the total squared deviation of the observed counts from that. When is large, approximately follows a chi-square distribution with degrees of freedom.
- Reject at significance level if
where the threshold is defined by (upper -quantile, as with and ). Large means the counts are too uneven to be uniform; only the upper tail is used.
What is the chi-square distribution? If are i.i.d. , then
is a chi-square random variable with degrees of freedom, written .
Why is approximately under .
Assume is true. Each lands in interval with probability , independently of the others, so the count is binomial:
By the CLT (a binomial is a sum of Bernoullis), the standardized count is approximately standard normal for large :
If the were independent, would be by the definition above. Writing this sum out,
But the are not independent: the counts satisfy , one linear constraint, so only of them are free. The precise result (Pearson) is that this constraint costs exactly one degree of freedom and the factor is exactly what compensates: , not . The heuristic to remember is: approximately normal terms, one constraint, degrees of freedom.
The threshold cuts off an upper tail of area . Under the statistic lands in that tail with probability only , so landing there is taken as evidence against uniformity.
Example. Twenty numbers are generated from an RNG:
Are these from a uniform distribution on , at significance level ?
Step 1. Divide into subintervals. With only numbers we cannot meet ; take , which at least satisfies . (This is a hand-sized illustration — a real test would use thousands of numbers.)
Step 2. numbers are already generated.
Step 3. Count how many fall in each subinterval. Expected count per interval: .
| interval | numbers in it | ||||
|---|---|---|---|---|---|
| 1 | 0.10, 0.08, 0.23, 0.15, 0.05, 0.00 | 6 | 5 | ||
| 2 | 0.32, 0.41, 0.28, 0.49, 0.37 | 5 | 5 | ||
| 3 | 0.54, 0.67, 0.60, 0.73 | 4 | 5 | ||
| 4 | 0.76, 0.89, 0.95, 0.82, 0.91 | 5 | 5 | ||
| total | 20 | 20 |
Step 4. Compute the test statistic:
Step 5. Compare with the threshold. Degrees of freedom , and from the chi-square table
Since , we do not reject at the level: there is no evidence that these numbers are non-uniform.
Remark. “Do not reject” is not “proved uniform.” First, the test only looks at the marginal distribution — a sequence like would pass the uniformity test easily while being obviously non-random, which is why a test for independence is also needed (§3.4.2). Second, with the test has very little power; the counts would have to be wildly off to produce a above .
Serial tests (higher-dimensional tests)
The one-dimensional test only checks the marginal distribution. The serial test checks a consequence of the full hypothesis:
If the are i.i.d. , then the non-overlapping -tuples
are uniformly distributed over the hypercube .
This is an implication, not an equivalence: , so failing disproves . That is enough for a test — if the tuples are not uniform on the cube, the numbers are not i.i.d. .
Case .
- Divide the square into subsquares of equal size.
- Generate pairs , , …, . Note each is used once: numbers give pairs.
- Let be the number of ’s falling in subsquare . The expected count per square is , so
( cells, one constraint , hence degrees of freedom — same counting as in §3.4.1).
- Reject at level if ; see [[Review of Prob and Stats#2.6.3. Statistical tables (, , $ chi 2$)]].
Why this is an indirect test of independence. The one-dimensional test cannot see dependence at all: a sequence can have a perfectly uniform histogram and still be highly predictable. The serial test looks at successive values jointly, so such structure shows up as clumping in the square.
Limitations.
- Indirect. Passing the serial test does not prove independence; it only means no dependence was detected at the resolution used. RANDU, for instance, passes comfortably in and fails only in , where its 15 planes appear.
- Costly for large . The number of cells is , and the rule forces — exponential in . With and that is already tuples, i.e. million random numbers. In practice one uses a small for larger , or switches to a theoretical test such as the spectral test, which examines all dimensions at once without sampling.
3.4.2. Test for independence (runs test)
What “runs” means. A run up is an unbroken subsequence of ’s that is monotonically increasing; the run ends as soon as the next number is smaller. The sequence is thus chopped into maximal ascending pieces, and the test looks at how long those pieces are. The name is literal: how far does the sequence “run” upward before turning around?
The idea is that the lengths of these runs have a known distribution when the are i.i.d., and this distribution depends on the order of the numbers, not just on their values. That is exactly what the frequency test cannot see.
Example (the same 20 numbers as in §3.4.1). Mark where and where a run ends:
The run lengths are (they sum to , as they must).
The counts. Let
Lengths are pooled into one category because they are rare, so their individual counts would be too small for the approximation to hold — the same reason the frequency test wants per cell.
For the example: , , , , .
Expected counts. Under the expected number of runs of each length is , where the are universal constants (they do not depend on the distribution, only on the ordering being random):
Note : a random sequence of length splits into about runs up. Runs of length are the most common, not length .
The test statistic.
where the are constants tabulated in the textbook (Law & Kelton, p. 408); the matrix is symmetric, with entries in the thousands — the first row begins
Why the double sum, unlike the statistic of §3.4.1? Because the are strongly correlated with one another: a long run uses up numbers that then cannot start short runs, so an excess of forces a deficit elsewhere. A plain sum of squared deviations would therefore not have a chi-square distribution. The matrix is (up to scaling) the inverse of the covariance matrix of the vector , and multiplying by it removes those correlations — this is the general recipe for turning a correlated normal vector into a chi-square variable.
Decision rule. For large (the textbook recommends ), under
has approximately a chi-square distribution with 6 degrees of freedom — not , because here no constraint like ties the six counts together. Reject at significance level if
with the threshold read from [[Review of Prob and Stats#2.6.3. Statistical tables (, , $ chi 2$)]]: e.g. .
(The 20-number example cannot be carried further: with the chi-square approximation is meaningless. It only illustrates how the are counted.)
In practice, perform the runs test first. Two reasons:
- The frequency test’s null distribution was derived assuming independence — that is what made binomial in §3.4.1. If the numbers are dependent, the threshold is not valid, so testing uniformity first can give a meaningless answer.
- Dependence is the more damaging defect. A generator whose output is uniform but correlated will quietly bias any simulation, whereas mild non-uniformity is often visible and correctable.