Last active
March 15, 2022 18:04
-
-
Save tupui/6ecfa0370dcea8399b0a410a19f891a2 to your computer and use it in GitHub Desktop.
Convergence on the value of Pi using Monte Carlo vs QMC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Convergence of Pi using QMC. | |
--------------------------- | |
MIT License | |
Copyright (c) 2022 Pamphile Tupui ROY | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
import numpy as np | |
from scipy.stats import qmc | |
import matplotlib.pyplot as plt | |
n_conv = 999 | |
MIN_POWER = 4 | |
POWER_MAX = 17 | |
ns_gen = 2 ** np.arange(MIN_POWER, POWER_MAX + 1) | |
dim = 2 | |
def func(x): | |
radius = (x[:, 0]**2 + x[:, 1]**2) ** .5 | |
in_circle = len(np.where(radius <= 1)[0]) | |
return 4 * in_circle / x.shape[0] | |
def conv_method(samples, func, n_conv): | |
evals = [func(sample) for sample in samples] | |
ref = np.pi | |
squared_errors = (ref - np.array(evals)) ** 2 | |
rmse = (np.sum(squared_errors) / n_conv) ** 0.5 | |
return rmse | |
# Analysis | |
def sampler_mc(ns, dim): | |
sampler_ = lambda x: np.random.random((x, dim)) | |
samples_ = [sampler_(ns) for _ in range(n_conv)] | |
return np.array(samples_) | |
def sampler_sobol(ns, dim): | |
def _sampler_sobol(ns): | |
engine = qmc.Sobol(d=dim, scramble=True) | |
return engine.random(ns) | |
samples_ = [_sampler_sobol(ns) for _ in range(n_conv)] | |
return np.array(samples_) | |
samplers = { | |
"MC": [sampler_mc, []], | |
"Sobol'": [sampler_sobol, []], | |
} | |
for ns in ns_gen: | |
print(f'-> ns={ns}') | |
for sampler_ in samplers: | |
sample_ = samplers[sampler_][0](ns, dim) | |
conv_res = conv_method(sample_, func, n_conv) | |
samplers[sampler_][1].append(conv_res) | |
for sampler_ in samplers: | |
samplers[sampler_][1] = np.array(samplers[sampler_][1]) | |
fig, ax = plt.subplots(figsize=(5, 5)) | |
for sampler_ in samplers: | |
ax.plot( | |
ns_gen, np.log2(samplers[sampler_][1]), | |
label=sampler_ | |
) | |
ax.set_xlabel(r'$N_s$') | |
ax.set_xscale('log') | |
ax.set_xticks(ns_gen) | |
ax.set_xticklabels([fr'$2^{{{ns}}}$' for ns in np.arange(MIN_POWER, POWER_MAX + 1)]) | |
ax.set_ylabel(r'$\log (\epsilon (\mu))$') | |
fig.legend(labelspacing=0.7, bbox_to_anchor=(0.9, 0.9)) | |
fig.tight_layout() | |
Author
tupui
commented
Mar 15, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment