In [1]:
from collections import namedtuple
import datetime
import numpy as np
import spacepy.plot as spp
import spacepy.toolbox as tb
import pymc as mc
import tqdm
In [12]:
x = mc.Uniform('x', 0, 1)
y = mc.Uniform('y', 0, 1)
# @mc.deterministic(plot=True)
# def pi(x=x, y=y):
# inside = (x**2 + y**2) <= 1
# outside = (x**2 + y**2) > 1
# return 4*inside/outside
model = mc.MCMC((x, y))
In [ ]:
model.sample(50000, burn=0, burn_till_tuned=False)
In [ ]:
mc.Matplot.plot(model)
In [ ]:
inside = np.sum(x.trace()**2 + y.trace()**2 < 1)
total = len(x.trace())
pi = 4*inside/total
print('PI: 4*{0}/{1}={2}'.format(inside, total, pi))
In [ ]:
dat = namedtuple('Pi', 'niter error')
data = []
for i in tqdm.tqdm(tb.logspace(100, 1e7, 30)[::-1]):
x = mc.Uniform('x', 0, 1)
y = mc.Uniform('y', 0, 1)
model = mc.MCMC((x, y))
model.sample(i, burn=10, progress_bar=False)
inside = np.sum(x.trace()**2 + y.trace()**2 < 1)
total = len(x.trace())
pi = 4*inside/total
data.append(dat(i, np.abs((pi-np.pi)/np.pi)))
# print(i, pi, np.abs((pi-np.pi)/np.pi))
In [21]:
its = [v.niter for v in data]
err = [v.error for v in data]
spp.plt.loglog(its, err, '.-')
spp.plt.plot(its, 1/np.sqrt(its)*0.4)
spp.plt.xlabel('Number of draws')
spp.plt.ylabel('Percent error')
Out[21]:
In [ ]: