import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import mpld3
from numpy.random import rand, randn
mpld3.enable_notebook()
def estimate_uniform(N):
x = 2 * rand(N)
g = 2 / (1 + pow(x,5))
return np.mean(g)
estimate_uniform(1000)
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))
estimate_variance(100, 10000, estimate_uniform, 1.05355)
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
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)
estimate_gauss(1000)
estimate_variance(100, 1000, estimate_gauss, 1.05355)
ax.loglog(Ns, [estimate_variance(100, N, estimate_gauss, 1.05355) for N in Ns])
fig
def estimate_stratify(N):
x = 2 * (rand(N) + range(N)) / N
g = 2 / (1 + pow(x,5))
return np.mean(g)
estimate_stratify(10000)
estimate_variance(100, 10000, estimate_stratify, 1.053547084316272)
ax.loglog(Ns, [estimate_variance(100, N, estimate_stratify, 1.053547084316272) for N in Ns])
fig
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