Last active
February 8, 2020 00:26
-
-
Save edoakes/c0e45ca1bc3e27ad7646314b65ff19e7 to your computer and use it in GitHub Desktop.
Monte Carlo Pi Estimation in Python
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 math | |
import random | |
import time | |
def sample(num_samples): | |
num_inside = 0 | |
for _ in range(num_samples): | |
x, y = random.uniform(-1, 1), random.uniform(-1, 1) | |
if math.hypot(x, y) <= 1: | |
num_inside += 1 | |
return num_inside | |
def approximate_pi(num_samples): | |
start = time.time() | |
num_inside = sample(num_samples) | |
print("pi ~= {}".format((4*num_inside)/num_samples)) | |
print("Finished in: {:.2f}s".format(time.time()-start)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment