|
| 1 | +####################################################################### |
| 2 | +# Copyright (C) # |
| 3 | +# 2018 Shangtong Zhang(zhangshangtong.cpp@gmail.com) # |
| 4 | +# Permission given to modify the code as long as you keep this # |
| 5 | +# declaration at the top # |
| 6 | +####################################################################### |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import matplotlib |
| 10 | +matplotlib.use('Agg') |
| 11 | +import matplotlib.pyplot as plt |
| 12 | +from tqdm import tqdm |
| 13 | + |
| 14 | +# for figure 8.7, run a simulation of 2 * @b steps |
| 15 | +def b_steps(b): |
| 16 | + # set the value of the next b states |
| 17 | + # it is not clear how to set this |
| 18 | + distribution = np.random.randn(b) |
| 19 | + |
| 20 | + # true value of the current state |
| 21 | + true_v = np.mean(distribution) |
| 22 | + |
| 23 | + samples = [] |
| 24 | + errors = [] |
| 25 | + |
| 26 | + # sample 2b steps |
| 27 | + for t in range(2 * b): |
| 28 | + v = np.random.choice(distribution) |
| 29 | + samples.append(v) |
| 30 | + errors.append(np.abs(np.mean(samples) - true_v)) |
| 31 | + |
| 32 | + return errors |
| 33 | + |
| 34 | +def figure_8_7(): |
| 35 | + runs = 100 |
| 36 | + branch = [2, 10, 100, 1000] |
| 37 | + for b in branch: |
| 38 | + errors = np.zeros((runs, 2 * b)) |
| 39 | + for r in tqdm(np.arange(runs)): |
| 40 | + errors[r] = b_steps(b) |
| 41 | + errors = errors.mean(axis=0) |
| 42 | + x_axis = (np.arange(len(errors)) + 1) / float(b) |
| 43 | + plt.plot(x_axis, errors, label='b = %d' % (b)) |
| 44 | + |
| 45 | + plt.xlabel('number of computations') |
| 46 | + plt.xticks([0, 1.0, 2.0], ['0', 'b', '2b']) |
| 47 | + plt.ylabel('RMS error') |
| 48 | + plt.legend() |
| 49 | + |
| 50 | + plt.savefig('../images/figure_8_7.png') |
| 51 | + plt.close() |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + figure_8_7() |
0 commit comments