Created
March 5, 2013 11:36
-
-
Save tomonari-masada/5089710 to your computer and use it in GitHub Desktop.
Sampling from a normal distribution by Metropolis Monte Carlo
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 sys | |
import math | |
import random | |
def invariant_distribution(x): | |
return math.exp(- 0.5 * x ** 2 / (0.3 * 0.3)) | |
def next_state(x, dx): | |
return x + dx * (random.uniform(0.0, 1.0) - 0.5) | |
size = 100000 | |
dx = 1.0 | |
now = 0.0 | |
results = [] | |
for i in range(size): | |
next = next_state(now, dx) | |
probability = min(1.0, | |
invariant_distribution(next) | |
/ invariant_distribution(now)) | |
if probability > random.uniform(0.0, 1.0): | |
now = next | |
results.append(now) | |
step = 0.01 | |
freq = {} | |
for result in results: | |
res = step * round(result / step) | |
if res == -0.0: | |
res == 0.0 | |
freq[res] = freq.get(res, 0) + 1 | |
total = 0.0 | |
for res in sorted(freq): | |
total += freq[res] | |
for res in sorted(freq): | |
print "%.2lf\t%.6lf" % (res, freq[res] / (total * step)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment