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.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Worked example: triangular density f(x)=2x, first three seeded draws
- •Reference case: uniform target on [0,4], seeded draws
- •Sample: exponential-shaped density, first three seeded draws