Rejection samplingMediumnumpysamplingmonte-carloprobability
Rejection sampling
Background
Rejection sampling draws samples from a target density you can evaluate but not easily sample. On a bounded interval with , you throw darts uniformly under the bounding box and keep the of darts that land under the curve. The accepted values are distributed exactly according to .
Problem statement
Implement rejection_sample(f, xmin, xmax, fmax, n, seed=0) returning n samples from f:
- Propose and .
- Accept if , else reject.
- Repeat until
nsamples are accepted.
Use np.random.default_rng(seed).
Input
f— callable target density (unnormalized is fine), evaluable on .xmin,xmax—floatinterval bounds.fmax—float, an upper bound onfover the interval.n—int, number of accepted samples to return.seed—int, RNG seed.
Output
An np.ndarray of shape (n,): accepted samples, all within [xmin, xmax].
Examples
Example 1
Input: f(x) = 2x on [0, 1], fmax = 2, n = 10000
Output: ~10000 samples whose mean ≈ 0.667 (the mean of the triangular density 2x)
Explanation: darts under the line are kept; larger is accepted more often, so the samples concentrate toward 1, with mean .
Constraints
- Accept exactly when (uniform height test against the curve).
- Keep proposing until
nsamples are accepted; all returned values lie in[xmin, xmax]. fmaxmust dominatefon the interval for correctness.
Notes
- Efficiency depends on the acceptance rate = (area under ) / (box area); a loose wastes many proposals.
- Rejection sampling needs no inverse CDF — only the ability to evaluate and bound it.
Python
Loading...
This problem ships 5 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •All samples lie in the interval
- •Triangular density 2x has mean ~ 2/3
- •Uniform target recovers a uniform mean
- •Returns exactly n samples
- •Reproducible with the same seed