4. Generating Random Variates
How to turn i.i.d. U(0,1) random numbers into observations from the distributions a model actually needs — the inverse transform and composition methods, and what makes a variate-generation algorithm good.
Goal. Study algorithms that produce observations (realizations) from some desired input distribution, given a stream of i.i.d. random numbers.
Chapter 3 produced the raw material: uniform random numbers. This chapter turns them into random variates from whatever distribution the model calls for — e.g. the exponential interarrival and service times of an queue.
4.1. Structure
- It is essential to have a statistically reliable underlying RNG. Every algorithm below assumes its input really is i.i.d. ; a defective generator corrupts every variate built from it.
Factors in choosing an algorithm.
1. Exactness. An algorithm is exact if the variates it produces have exactly the desired distribution, not merely approximately.
Example of an inexact method. To generate :
- Generate i.i.d. .
- Return .
The moments come out right:
and by the CLT the sum is approximately normal. But it is not exact. Since each , the output always satisfies
whereas a true variable has range . The algorithm can never produce a value beyond , so it truncates both tails — exactly the region that matters most in reliability, risk, and rare-event studies. It is also wasteful: 12 random numbers per variate. Avoid it; use an exact method (§4.2.5) instead.
2. Efficiency.
- memory usage;
- execution time, including setup time (some algorithms precompute tables; that cost is paid once but must be counted).
3. Simplicity: easy to understand, implement, and debug. There is a trade-off between efficiency and simplicity — the fastest algorithm is rarely the clearest.
4. If possible, use exactly one random number per random variate. Reasons:
- Simplicity.
- Synchronization. When comparing two systems with common random numbers (§3.3, practical issue 3), we want the -th variate in system A to be built from the same as in system B. If one system consumes a variable number of uniforms per variate, the two streams drift out of step and the comparison loses its sharpness.
- Monotonicity. With one uniform per variate and , the variate is a monotone function of . This is what makes variance-reduction techniques such as antithetic variates work.
4.2. RVG Algorithms
Direct methods — build the variate straight from the definition of the distribution:
- Inverse transform — universally applicable in principle, but may be hard to implement.
- Composition ⎫
- Convolution ⎭ — apply only to input distributions of a specific form (mixtures and sums, respectively).
When these fail — that is, when has no usable closed form and the distribution is neither a convenient mixture nor a convenient sum (the normal, gamma, and beta distributions are the standard examples) — fall back on:
- Acceptance–rejection method.
- Special techniques, e.g. for normal random variables.
4.2.1. Inverse Transform Method
Continuous case. Let be a continuous r.v. with c.d.f. .
Algorithm.
- Generate .
- Return .
The catch is step 2: must be computed, and for many distributions (normal, gamma, beta) it has no closed form.
Proof that the output has c.d.f. .
The last step is the definition of the uniform distribution: for any , and here is indeed in because it is a probability. So the c.d.f. of the generated is , exactly — the method is exact.
Example: . Here for . Set and solve:
Algorithm.
- Generate .
- Return .
Variant. Replace step 2 by “2′. Return .”
This is valid because whenever , so the two versions produce the same distribution. It saves one subtraction per variate — a genuine but small gain in a tight loop.
Two cautions, though:
- Monotonicity is lost. Version 2 is increasing in ; version 2′ is decreasing. Under 2, a large gives a long interarrival time in both of two systems being compared; under 2′ the correspondence is reversed. Where synchronization or antithetic variates matter, prefer 2.
- The value . An LCG can output (when ), and is undefined. Version 2 never has this problem, since . If 2′ is used, must be screened out.
Efficiency problem. The number of comparisons the chain performs equals , the index it returns. Since the algorithm returns exactly when , and , the number of comparisons is a random variable with the same distribution as the index, so by the definition of expectation,
If the probable values sit late in the list, this is close to : tiny jumps at and the big jumps only at the end.
Two fixes.
-
Binary search. Since is a sorted array, locate by bisection instead of scanning: comparisons instead of , whatever the probabilities.
-
Reorder the comparisons. Test the values in decreasing order of probability. Relabel so that and build the cumulative sums for that new order; then is as small as possible. The reordering is done once in setup, so it costs nothing at run time.
Example. with :
| order of testing | |
|---|---|
| as given: | |
| decreasing probability: |
More than twice as fast, for no cost beyond sorting once.
Does reordering change the simulation? No. The output distribution is exactly the same — each is still returned with probability , because the intervals of assigned to the values have the same widths ; only their positions along are permuted. The only thing that changes is the expected number of comparisons, i.e. the run time.
The one side effect: reordering destroys the monotone relationship between and , so the output is no longer as a function of . If synchronization or antithetic variates matter (see “Advantages” below), keep the natural order or use binary search, which preserves it.
Example: discrete uniform. , i.e. with for every , so .
The general algorithm becomes:
- Generate .
if u ≤ 0.01 return X = 1; else if u ≤ 0.02 return X = 2; … ; else return X = 100
But here the chain can be replaced by a formula. The first with is characterized by
so step 2 collapses to
— one multiplication and one ceiling, instead of up to 100 comparisons. (Equal probabilities are what make this possible; unequal ones need the search.)
Generalized inverse transform. To cover continuous, discrete, and mixed distributions in one statement:
- Generate .
- Return .
This is the same rule as before, written so it always makes sense. An ordinary inverse requires to be strictly increasing and continuous; a discrete is flat in places (so no unique inverse) and jumps in places (so some values of have no with at all). Taking the smallest whose has reached handles both defects, and reduces to the usual when is continuous and strictly increasing.
Advantages and disadvantages of the inverse transform method.
Disadvantages.
- Must invert the c.d.f., which may have no closed form (normal, gamma, beta).
- May not be the most efficient approach even when the inverse exists.
Advantages.
-
Easy to generate from truncated distributions. Truncating means restricting to an interval and renormalizing:
which is the original density chopped off outside and scaled up so the area is again 1.
Inverting costs nothing extra: generate and return
In words: instead of drawing uniformly over all of , draw it uniformly over the slice of the vertical axis. Every draw is usable — no rejection, one uniform per variate.
-
Facilitates variance reduction when comparing alternative systems. Let be the output of system 1 and that of system 2, and suppose we want the difference in mean cost,
so that is an unbiased estimator of the gap. Generate both by inverse transform, and . Since
the precision of the comparison is controlled entirely by how we couple and :
coupling 1. (independent) 2. (common random numbers) smaller 3. (antithetic) larger Case 2 is the useful one. Both and are non-decreasing, so a large pushes both and up and a small pushes both down: the two outputs move together, , and the variance of the difference drops. Note still, since . Monotonicity is exactly what the inverse transform provides and what a rejection-based method does not — hence “facilitates”.
(Case 3 is not useless in general; antithetic variates reduce variance when estimating a single mean by averaging and , where the negative correlation helps. It is only harmful here, where we take a difference.)
4.2.2. Composition
The name. The target distribution is composed of simpler ones — the way a mixture’s chemical composition lists its ingredients. The method is also called the mixture method: decompose into pieces you know how to sample from, pick a piece at random, then sample from it.
Setup. Use this when can be written as a convex combination of other c.d.f.s (finitely or infinitely many):
Equivalently, in terms of densities or mass functions,
Algorithm.
- Generate a positive random integer with (a discrete variate — use the inverse transform of §4.2.1).
- Return generated from the c.d.f. .
Proof. Conditioning on ,
Example: right trapezoidal distribution.
Split the formula into its two terms and read off the weights:
where is the density and on is a triangular density with , so .
Algorithm.
- Generate independent .
- If , return ; else return .
Here chooses the component ( with probability ) and generates from it.
Example: symmetric triangular distribution on .
Each half of the triangle has area , so take with
(each doubled so that it integrates to 1 on its own half). For the right piece, , and solving gives , i.e. after replacing by . The left piece is its mirror image.
Algorithm (composition).
- Generate independent .
- If , return ; else return .
The same distribution by inverse transform. The c.d.f. is
and , so corresponds to the left half. Solving gives ; solving gives .
- Generate .
- If , return ; else return .
Efficiency comparison (expected operations per variate):
| ’s | comparisons | additions | multiplications | square roots | |
|---|---|---|---|---|---|
| inverse | 1 | 1 | 1.5 | 1 | 1 |
| composition | 2 | 1 | 1.5 | 0 | 1 |
How the counts are obtained. Each row averages the two branches, which are taken with probability each; a subtraction counts as an addition. For the inverse method, the left branch uses one multiplication (), one square root and one addition, while the right branch uses one multiplication (), one square root and two additions ( and ) — so the average is additions, with 1 multiplication and 1 square root either way, plus the single comparison and the single uniform. For composition, has one addition and has two, giving the same average and the same one square root and one comparison, but no multiplication — the factor 2 never appears, because doubling the density was absorbed into choosing a half. The cost is that is spent on the coin toss and on the value, so two uniforms are consumed instead of one.
Conclusion. The two methods differ in exactly two places: composition saves one multiplication but spends one extra random number. Generating a random number is far more expensive than a multiplication, so the inverse transform is more efficient here. (It also keeps monotone in , which composition does not — see §4.2.1, advantage 4.)
4.2.3. Convolution
Setup. Let be i.i.d. with common c.d.f. , and define
The c.d.f. of is called the -fold convolution of with itself. Use this method whenever the target distribution is known to arise as such a sum.
Algorithm (to generate from ):
- Generate independently from .
- Return .
Why the proof is trivial. Unlike the inverse transform or composition, there is nothing to verify: was defined as the distribution of the sum, and the algorithm literally forms that sum from independent draws. Correctness is by construction. The work in this method lies elsewhere — in recognizing that the desired is a convolution of something samplable.
Example: sum of two exponentials. Let and . Then
Explanation of each step.
- Condition on (law of total probability, continuous version). To find , split according to the value that takes, weight each case by the density , and integrate over all — the continuous analogue of . The range is because . The purpose is to turn a two-variable event into a one-variable one.
- Use the condition, then drop it. Given , the event is , i.e. . Then, because , knowing says nothing about , so — the condition disappears. Also substitute .
- Substitute the c.d.f. of . , valid when . When the argument is negative and ( is never negative), so the integrand vanishes there; hence the upper limit drops from to .
- Expand and simplify. Multiply out and split into two integrals. In the second, : the cancels, leaving a constant.
- Evaluate. First integral: . Second: the integrand is the constant , so the integral is that constant times the interval length .
- Rewrite as a sum. Factor out : . The two terms in the bracket are and , i.e. of . Writing it this way exposes the pattern: for a sum of exponentials the same calculation, repeated, gives the terms .
Generalization: the Erlang distribution. Let be i.i.d. and . Repeating the argument gives
and is called an Erlang variable — the special case of the Gamma distribution with integer shape parameter.
Reading the formula. The sum is exactly for a Poisson variable with mean . This is the Poisson-process statement of §2.5: the -th arrival occurs by time if and only if at least arrivals have occurred by then. So “waiting for the -th event” and “counting events” are two views of the same process.
Algorithm for Erlang.
- Generate i.i.d. (each by inverse transform, §4.2.1).
- Return .
This is exact and trivially correct, but it costs uniforms and logarithms per variate. One improvement is free:
so multiply the uniforms first and take a single logarithm. The uniforms are still needed, which is why convolution becomes unattractive for large — and why the Gamma distribution with non-integer shape needs a different method (acceptance–rejection, §4.2.4).
Composition vs. convolution. Both write the target in terms of simpler distributions, but in opposite ways:
| composition | convolution | |
|---|---|---|
| decomposition | (weighted mixture) | (sum) |
| what you do | pick one component at random, sample it | sample all components, add them |
| uniforms used | 1 for the choice + those for one component | those for all components |
Example: symmetric triangular distribution, third method. Recall (§4.2.2)
Let and . The pair is uniform on the unit square (joint density ), so a probability is an area:
- Case . The line cuts off a right triangle at the origin with legs and :
- Case . Now the line cuts off the top-right corner, a right triangle with legs . Shaded area whole square minus that corner:
Differentiating gives the density of :
a triangle on with peak at . Subtracting 1 slides it to : has , which is on and on — exactly the target.
Algorithm (convolution).
- Generate .
- Return .
Why this beats both earlier methods. Add the new row to the table from §4.2.2:
| ’s | comparisons | additions | multiplications | square roots | |
|---|---|---|---|---|---|
| inverse | 1 | 1 | 1.5 | 1 | 1 |
| composition | 2 | 1 | 1.5 | 0 | 1 |
| convolution | 2 | 0 | 2 | 0 | 0 |
Convolution uses the same two uniforms as composition but eliminates the comparison, the multiplication, and above all the square root, at the price of half an extra addition. A square root is by far the most expensive operation in the table — many times the cost of an addition, and more than the cost of drawing a uniform — so removing it outweighs the second uniform, and convolution is the most efficient of the three for this distribution. (Against inverse transform, the trade is one extra uniform plus half an addition in exchange for dropping a comparison, a multiplication and a square root; the square root alone settles it.)
4.2.4. Acceptance–Rejection (AR)
Where it sits. Methods 1–3 (§4.2.1–4.2.3) are direct: they compute from the uniforms by a formula. Acceptance–rejection is the indirect method from the list in §4.2: it does not compute ; it generates candidates from an easier distribution and keeps only some of them. The arrow in the lecture outline (“rejection → indirect”) just records that classification.
When to use it. When the desired p.d.f. has a form too complex to invert or decompose.
Idea. Use a simple, easy-to-sample p.d.f. — a surrogate — that approximates from above, then correct for the difference by discarding a fraction of the draws.
Setup. Choose a majorizing function with
Then
so is not a density (its area exceeds 1), but its normalization
is a valid p.d.f. ( and ). is the surrogate we actually sample from.
AR algorithm.
- Generate .
- Generate , independent of .
- If , return (accept).
- Otherwise discard and go back to step 1.
On step 1: is generated from the surrogate , not from — that is the whole point. Since was chosen to be simple, this is done by one of the direct methods (typically inverse transform). is only a candidate for ; steps 3–4 decide whether it becomes one.
On step 3: the ratio lies in because . Comparing it with a uniform means: accept with probability . Where hugs this is near 1 (almost always accept); where is far above it is small (usually reject). The rejections thin out exactly the regions where over-samples relative to .
Proof that the output has c.d.f. . The returned is a candidate given that it was accepted, so
We compute the denominator first (it is also the efficiency, comment 2 below):
The numerator is the same calculation with the extra event , which after conditioning on just restricts the integral to :
Dividing,
Note the mechanism: cancels between the acceptance probability and the surrogate density , and cancels between numerator and denominator. Whatever shape has, the output is exactly — the choice of affects only speed, never correctness.
Comments.
-
Generating from must be much easier than generating from ; otherwise there is no point in using a surrogate. In practice, choose simple majorizing functions — piecewise constant or piecewise linear.
-
The algorithm loops until a pair with turns up. From the proof,
Why the average number of trials is : each pass through steps 1–3 is an independent trial with success probability (fresh and each time). The number of trials until the first success is therefore Geometric, whose mean is . So uniforms-pairs are consumed per variate on average — a large means a slow generator.
-
is called the efficiency of the AR method. We want it as close to 1 as possible, i.e. as tight around as possible — but a tighter is usually a more complicated one, harder to sample from. This is the same simplicity vs. efficiency trade-off as in §4.1.
Example. on (and elsewhere). Check: . The maximum of is , at .
First attempt: a flat majorizing function. Take on — the smallest constant that stays above . Then and on , i.e. is the density.
- Generate (e.g. with ).
- Generate , independent of .
- If , return .
- Otherwise go back to step 1.
Efficiency : on average three candidates (six uniforms) per accepted variate. The waste is visible in the figure — the rectangle under has area 3 while the bowl under has area 1, and everything in between is rejected.
Improvement: a tighter majorizing function. We need but with less area. On we have , so
with equality at . Its area is , so the efficiency rises to : on average candidates per variate instead of . The surrogate is on , a symmetric “V” density, easy to sample by inverse transform: its right half has c.d.f. , so , and a fair coin picks the sign.
- Generate ; set if , else . Then .
- Generate , independent of .
- If , return .
- Otherwise go back to step 1.
Each trial now costs three uniforms and a square root instead of two uniforms, but only trials are needed on average instead of — the trade-off of comment 3 in miniature.