Created
September 2, 2021 19:06
-
-
Save bllchmbrs/8e172905cbbda8043dc8ca8b42497265 to your computer and use it in GitHub Desktop.
Monte Carlo
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
import argparse | |
import time | |
import random | |
import math | |
from ray.util.multiprocessing import Pool | |
parser = argparse.ArgumentParser(description="Approximate digits of Pi using Monte Carlo simulation.") | |
parser.add_argument("--num-samples", type=int, default=1000000) | |
SAMPLE_BATCH_SIZE = 100000 | |
def sample(num_samples): | |
num_inside = 0 | |
for _ in range(num_samples): | |
x = random.uniform(-1, 1) | |
y = random.uniform(-1, 1) | |
if math.hypot(x, y) <= 1: | |
num_inside += 1 | |
return num_inside | |
def approximate_pi(num_samples): | |
print("Estimating using", args.num_samples, "samples...") | |
pool = Pool() | |
num_inside = 0 | |
for result in pool.map(sample, [SAMPLE_BATCH_SIZE for _ in range(num_samples//SAMPLE_BATCH_SIZE)]): | |
num_inside += result | |
print("pi ~= {}".format((4*num_inside)/num_samples)) | |
if __name__ == "__main__": | |
args = parser.parse_args() | |
start = time.time() | |
approximate_pi(args.num_samples) | |
print("Finished in: ", time.time()-start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment