Last active
December 10, 2021 04:29
-
-
Save modanesh/80c28192dc56f4f32994cf9a4b8eb93b to your computer and use it in GitHub Desktop.
Generate normally-distributed random samples from uniform samples by rejection sampling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
import bisect | |
from scipy import stats | |
rng = np.random.default_rng() | |
desired_variance = 1 | |
desired_mean = 0 | |
uni_rand = rng.uniform(low=-desired_variance*3, high=desired_variance*3, size=1000) | |
_ = plt.hist(uni_rand, bins='auto') | |
plt.show() | |
bins_edges = np.linspace(start=-desired_variance*3, stop=desired_variance*3, num=100) | |
bins_centers = (bins_edges[0:-1] + bins_edges[1:]) / 2 | |
desired_bin_density = stats.norm(desired_mean, desired_variance).pdf(bins_centers) | |
for i in range(10000): | |
uni_rand_candidate = rng.uniform(low=-desired_variance*3, high=desired_variance*3) | |
candidate_bin = bisect.bisect(bins_edges, uni_rand_candidate) - 1 | |
bin_counts, _ = np.histogram(uni_rand, bins=bins_edges, density=True) | |
if bin_counts[candidate_bin] < desired_bin_density[candidate_bin]: | |
uni_rand = np.append(uni_rand, uni_rand_candidate) | |
_ = plt.hist(uni_rand, bins='auto') | |
plt.show() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment