| import random | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| def p(x): | |
| return 6 * (1 - x) * x if 0 < x < 1 else 0 | |
| random.seed(12345) | |
| S = [] | |
| x = 0.5 | |
| T = 200000 | |
| sigma = 0.1 | |
| rej = 0 | |
| for t in range(T): | |
| xp = x + random.gauss(0, sigma) | |
| px = p(x) | |
| pxp = p(xp) | |
| if px < pxp or px * random.uniform(0, 1) <= pxp: | |
| x = xp | |
| else: | |
| rej += 1 | |
| S.append(x) | |
| x = np.linspace(0, 1, 1000) | |
| y = [p(e) for e in x] | |
| plt.hist(S, bins=40, density=True) | |
| plt.plot(x, y) | |
| plt.show() |