Inverse transform sampling
The question
Can you shape a CDF so that 800 uniform draws produce a chosen four-bin histogram?
Build the sampler, then separate its distribution from the noise in one run.
- 1 SeeShape a CDF to match a histogram.
- 2 TryTest an exponential sampler.
- 3 ProveBuild the quantile proof.
- 4 ApplyGenerate values and audit a sampler.
Before you start · 3 quick checks on CDFs, uniform probabilities and logarithms
Two ideas before you start
2 ideasA uniform input is a probability level
A constant density on the unit interval, with a selected interval shaded.
A uniform draw selects a level between zero and one. An interval's length is its probability.
Exact definition
Write \(U\sim\operatorname{Uniform}(0,1)\). For \(0\le a\le b\le1\), \(P(a\lt U\le b)=b-a\). Each endpoint has probability zero. The mathematical model uses a continuous uniform variable; computer draws have finite precision.
A CDF records probability already accumulated
The CDF of a uniform variable on an interval, with a selected position marked.
The horizontal coordinate is a possible value; the vertical coordinate is accumulated probability. Keep those roles separate.
Exact definition
A cumulative distribution function is \(F(x)=P(X\le x)\). It is nondecreasing, right-continuous, and tends to zero at negative infinity and to one at positive infinity. Here the card uses a uniform variable on \([0,4]\), so \(F(x)=x/4\) inside that interval. Outside it, extend the graph by zero on the left and one on the right. See PMF, PDF and CDF for how a CDF relates to masses and density areas.
Refresher: infimum and right-continuity
The infimum of a nonempty set bounded below is its greatest lower bound. It need not belong to the set. Right-continuity means \(F(x+h)\to F(x)\) as positive \(h\) tends to zero. For a CDF, the events \(\{X\le x+h\}\) decrease to \(\{X\le x\}\); continuity of probability for decreasing events gives this limit. These facts will let the proof include jumps and flat stretches, where an ordinary inverse may not exist.
We use real-valued random variables. A CDF describes a probability distribution, not a guarantee that any finite sample will have precisely those proportions.
Build a sampler for the target
- Drag the three CDF handles vertically, or focus one and use the arrow keys.
- Press Run my sampler to map uniform inputs through your curve and compare the output with the target.
- Edit and rerun, or move to the second target. Reset clears your result.
| Bin | Target | Implied | Count |
|---|
Read a uniform draw as a height on the CDF. Move horizontally to the first place the curve reaches that height, then down to the value axis. This reverses the usual direction of reading a CDF. A larger vertical rise across a bin gives that bin a larger output probability. A flat section receives no interval of input levels.
The target specifies probability spread uniformly within each bin. The sampler uses straight segments between the handles. Under an ideal continuous uniform input, matching every bin probability also matches this entire target distribution. That conclusion would not hold for an arbitrary curved density inside each bin.
What the score measures
The distribution score is \(100(1-D)\), where \(D=\tfrac12\sum_i|p_i-t_i|\), \(p_i\) is your curve's probability in bin \(i\), and \(t_i\) is the target probability. A perfect distribution score means these bin probabilities agree. The sample discrepancy uses observed proportions instead. It can remain positive even for a perfect curve.
Each run uses the same seeded inputs, making edits comparable. Repeating Run without changing the curve repeats the result. This is a teaching experiment, not a test of the generator's independence. Endpoints are held at \((0,0)\) and \((4,1)\); arrow keys move by 0.01, Page Up or Page Down by 0.1, and Home or End moves to the neighboring handle's height.
Test an exponential sampler
Suppose a simulation needs exponential waiting times with rate \(\lambda\gt0\) per minute. Its CDF is \(F(x)=1-e^{-\lambda x}\) for \(x\ge0\), and zero for negative \(x\). The exponential distribution lesson explains when this waiting-time model is appropriate.
Turn a level into a waiting time
Set \(F(x)=u\), with \(0\lt u\lt1\). Rearranging gives \(e^{-\lambda x}=1-u\), so taking natural logarithms gives
\[Q(u)=\frac{-\ln(1-u)}{\lambda}.\]The logarithm receives a positive argument. Its value is negative here, and the leading minus sign makes the time positive. The rate carries inverse-time units, so division produces minutes. We assume the rate is fixed during each simulated wait.
- Choose the input level and rate with the sliders.
- Use the formula to reach each stated goal; these are applications of the result just revealed.
Endpoints and numerical implementation
For this exponential formula, \(u=0\) gives zero and \(u=1\) gives an infinite limit. The general quantile definition below is restricted to the open interval, so it need not assign either endpoint. This page's demonstration uses a finite grid strictly inside that interval. A generator that can return an endpoint needs an explicit endpoint convention.
The implementation evaluates the numerator as -Math.log1p(-u). This avoids first subtracting a very small input from one, which can lose significant digits. It does not turn finite precision into exact sampling. A finite uniform grid cannot reach arbitrarily far into an unbounded tail.
Because \(1-U\) is also uniform on \((0,1)\), the shortcut \(-\ln(U)/\lambda\) has the same exponential distribution. It is a decreasing map of the input, though, so it is not the quantile: it sends a small input level to a long wait. Use the quantile form when the order of inputs matters, for example when reusing the same inputs to compare two rates.
If an inverse has no convenient formula, a monotone search can locate where the CDF first reaches the selected level. A search must bracket that crossing and control its error. An inaccurate CDF or inverse produces a different distribution, even if many samples are drawn. The Monte Carlo pricing lesson distinguishes sampling uncertainty from error in the model being sampled.
Why the output has the requested CDF
Let \(F\) be a CDF on the real line and let \(U\sim\operatorname{Uniform}(0,1)\). For \(0\lt u\lt1\), define the generalized inverse, or quantile, by
\[Q(u)=\inf\{x\in\mathbb R:F(x)\ge u\}.\]Then \(X=Q(U)\) has CDF \(F\). No positive density, strict increase, or differentiability is assumed. For the proof write \(A_u=\{t:F(t)\ge u\}\) and \(q=\inf A_u\). Each proof choice concerns these objects under the stated assumptions.
A jump of the CDF gives an interval of input levels the same output. That creates a point mass. A flat stretch of the CDF makes the quantile skip an interval of output values. These are different phenomena: a point mass concentrates probability at one value, while a flat stretch leaves an interval with no probability.
For a continuous, strictly increasing CDF, the generalized inverse agrees with the ordinary inverse on probability levels strictly between zero and one. At a jump, the rule is the first point that reaches or exceeds the level; requiring exact equality can leave no solution. For a discrete table sorted by output value, accumulate the probabilities and choose the first cumulative total at least as large as the draw.
Generate values and check the rule
Use what you found above. Each problem has hints and a worked solution. Enter a decimal; answers within 0.0005 of the unrounded value are accepted. The tolerance is for arithmetic practice, not a claim about the error of a simulation.
Further reading
- S. Ross, Simulation, chapter on generating random variables.
- L. Devroye, Non-Uniform Random Variate Generation, chapter II, general principles.