Skip to content

Instantly share code, notes, and snippets.

@modanesh
Created December 9, 2021 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save modanesh/a96aeb77b91e309aaa28fe96d913c171 to your computer and use it in GitHub Desktop.
Save modanesh/a96aeb77b91e309aaa28fe96d913c171 to your computer and use it in GitHub Desktop.
Box-Muller transformation
import math
import random
import matplotlib.pyplot as plt
uni_rand_1 = []
uni_rand_2 = []
gauss_samples_1 = []
gauss_samples_2 = []
for i in range(1000):
random_1 = random.random()
random_2 = random.random()
uni_rand_1.append(random_1)
uni_rand_2.append(random_2)
gauss_samples_1.append(math.sqrt(-2 * math.log(random_1)) * math.cos(2 * math.pi * random_2))
gauss_samples_2.append(math.sqrt(-2 * math.log(random_1)) * math.sin(2 * math.pi * random_2))
_ = plt.hist(uni_rand_1, bins='auto')
plt.show()
_ = plt.hist(uni_rand_2, bins='auto')
plt.show()
_ = plt.hist(gauss_samples_1, bins='auto')
plt.show()
_ = plt.hist(gauss_samples_2, bins='auto')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment