# Exercise - Rejection Sampling

## Introduction

Rejection sampling is a simple and straight forward algorihtm to generate samples for distributions, which a hard or impossible to sample from, using a second enclosing distribtuion. Using the enclosing function we will sample points and accept them as sample points for our desired distribution if they lie under the desired distribution curve and otherwise reject them.

## Requirements

### Knowledge

To complete this exercise notebook, you should possess knowledge about the following topics.

• Rejection Sampling

### Python Modules

import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import norm

%matplotlib inline

## Exercise

We want to sample from the green distribution$p(x)$ below.

But for now we assume that we can't sample from$p(x)$ directly, but we can sample from the red one$q(x)$, and we can compute$p(x)$ at each position$x$.

size=40
sigma_square_1 = 4.0
sigma_square_2 = 4.0
mu_1, sigma_1 = -2.5,np.sqrt(sigma_square_1)
mu_2, sigma_2 = 3.5,np.sqrt(sigma_square_1)
prob_1 = 0.4

rv_1 = norm(loc = mu_1, scale = sigma_1)
rv_2 = norm(loc = mu_2, scale = sigma_2)
x_ = np.arange(-14, 16, .1)

p_green = lambda x: prob_1 * rv_1.pdf(x) + (1-prob_1) * rv_2.pdf(x)
plt.plot(x_, p_green(x_) , "g-",label='$p(x)$')

sigma_red,mu_red = 5. , 1.
q_red = norm(loc = mu_red, scale = sigma_red)

plt.plot(x_, q_red.pdf(x_) , "r-",label='$q(x)$')
plt.legend()

_ = plt.xlabel("x")

Implement rejection sampling to get a sample from$p(x)$ by

• sampling from$q(x)$ and
• rejecting or accept some of the samples
• visualize the sample.

#### Hint

Since we need an enclosing function you will need to scale$q(x)$.

# x-values of red points are rejected
# x-values of green point are accepted
plt.plot(x_, p_green(x_) , "g-")
plt.plot(x_, f_red(x_)  , "r-")
plt.plot(samples, y_accept, 'g.', label='Samples')
plt.plot(rejected_samples, y_reject, 'r.', label='Samples')
_ = plt.hist(samples, bins=50, density=True)
plt.plot(x_, p_green(x_) , "g-")

The following license applies to the complete notebook, including code cells. It does however not apply to any referenced external media (e.g., images).

Exercise - Rejection Sampling
by Christian Herta, Klaus Strohmenger