In [1]:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import mpld3
from numpy.random import rand, randn
In [2]:
mpld3.enable_notebook()
In [3]:
def estimate_uniform(N):
    x = 2 * rand(N)
    g = 2 / (1 + pow(x,5))
    return np.mean(g)
In [6]:
estimate_uniform(1000)
Out[6]:
1.0781283343600983
In [7]:
def estimate_variance(nTrials, N, estimate_fn, real_answer):
    estimates = np.array([estimate_fn(N) for i in range(nTrials)])
    return np.mean(pow(estimates - real_answer, 2))
In [12]:
estimate_variance(100, 10000, estimate_uniform, 1.05355)
Out[12]:
5.6912656802815665e-07
In [31]:
Ns = np.logspace(1,5,11).astype(int)
fig = plt.figure()
ax = fig.gca()
ax.loglog(Ns, [estimate_variance(100, N, estimate_uniform, 1.05355) for N in Ns])
ax.set_xlabel('samples')
ax.set_ylabel('variance')
fig
Out[31]:
In [14]:
def estimate_gauss(N):
    x = abs(randn(N))
    p = 2 * np.exp(-pow(x, 2)/2)/(np.sqrt(2 * np.pi))
    g = 1 / (1 + pow(x,5)) / p
    g[x > 2] = 0
    return np.mean(g)
In [18]:
estimate_gauss(1000)
Out[18]:
1.0616038887356107
In [19]:
estimate_variance(100, 1000, estimate_gauss, 1.05355)
Out[19]:
0.00014450016251939181
In [32]:
ax.loglog(Ns, [estimate_variance(100, N, estimate_gauss, 1.05355) for N in Ns])
fig
Out[32]:
In [27]:
def estimate_stratify(N):
    x = 2 * (rand(N) + range(N)) / N
    g = 2 / (1 + pow(x,5))
    return np.mean(g)
In [28]:
estimate_stratify(10000)
Out[28]:
1.0535459884400233
In [29]:
estimate_variance(100, 10000, estimate_stratify, 1.053547084316272)
Out[29]:
5.689823469695994e-13
In [33]:
ax.loglog(Ns, [estimate_variance(100, N, estimate_stratify, 1.053547084316272) for N in Ns])
fig
Out[33]:
In [21]:
fig = plt.figure(figsize=(10,4))
ax = fig.add_subplot(1,2,1)
ax.axis([0, 1, 0, 1])
ax.set_aspect(1)
ax.grid(True)
ax.scatter(rand(100), rand(100))
ax = fig.add_subplot(1,2,2)
ax.axis([0, 1, 0, 1])
ax.set_aspect(1)
ax.grid(True)
ax.scatter((np.divide(range(100), 10) + rand(100))/10, (np.remainder(range(100), 10) + rand(100))/10)
fig
Out[21]:
In []: