#381Rejection samplingMedium

Rejection sampling

Background

Rejection sampling draws samples from a target density ff you can evaluate but not easily sample. On a bounded interval [xmin,xmax][x_{\min}, x_{\max}] with f(x)fmaxf(x) \le f_{\max}, you throw darts uniformly under the bounding box [xmin,xmax]×[0,fmax][x_{\min},x_{\max}]\times[0, f_{\max}] and keep the xx of darts that land under the curve. The accepted xx values are distributed exactly according to ff.

Problem statement

Implement rejection_sample(f, xmin, xmax, fmax, n, seed=0) returning n samples from f:

  1. Propose xU(xmin,xmax)x \sim \mathcal U(x_{\min}, x_{\max}) and uU(0,fmax)u \sim \mathcal U(0, f_{\max}).
  2. Accept xx if uf(x)u \le f(x), else reject.
  3. Repeat until n samples are accepted.

Use np.random.default_rng(seed).

Input

  • f — callable target density (unnormalized is fine), evaluable on [xmin,xmax][x_{\min}, x_{\max}].
  • xmin, xmaxfloat interval bounds.
  • fmaxfloat, an upper bound on f over the interval.
  • nint, number of accepted samples to return.
  • seedint, 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 y=2xy=2x are kept; larger xx is accepted more often, so the samples concentrate toward 1, with mean 01x2xdx=2/3\int_0^1 x\cdot 2x\,dx = 2/3.

Constraints

  • Accept exactly when uf(x)u \le f(x) (uniform height test against the curve).
  • Keep proposing until n samples are accepted; all returned values lie in [xmin, xmax].
  • fmax must dominate f on the interval for correctness.

Notes

  • Efficiency depends on the acceptance rate = (area under ff) / (box area); a loose fmaxf_{\max} wastes many proposals.
  • Rejection sampling needs no inverse CDF — only the ability to evaluate ff and bound it.
Python
Loading...

▶ 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