Skip to content

Instantly share code, notes, and snippets.

@kelly-sovacool
Last active November 7, 2019 22:14
Show Gist options
  • Save kelly-sovacool/d58f051059720b3b21841209a3abe48a to your computer and use it in GitHub Desktop.
Save kelly-sovacool/d58f051059720b3b21841209a3abe48a to your computer and use it in GitHub Desktop.
Monte Carlo simulation to estimate the value of Pi

monte-carlo-pi

Monte Carlo simulation to estimate the value of Pi

Runtime

Original Python 2 version

time python monte-carlo-pi.py
3.142226
python monte-carlo-pi.py  85.65s user 0.86s system 96% cpu 1:29.93 total

Python 3 single-processor version

time python monte-carlo-pi.py 
3.1410804
python monte-carlo-pi.py  60.82s user 0.55s system 98% cpu 1:02.55 total
""" Monte Carlo simulation to calculate Pi
Usage:
monte-carlo-pi.py [--sample-size=<n>] [--seed=<seed>]
monte-carlo-pi.py [--help]
Options:
-h --help Display this help message.
-n <n> --sample-size=<n> The sample size [default: 1e7].
--seed=<seed> Random seed for testing purposes.
"""
import docopt
import numpy as np
def main(args):
if args['--seed']:
np.random.seed(int(args['--seed']))
sample_size = int(args['--sample-size'])
space = np.random.rand(sample_size, 2)
radius = 1
num_points_within_radius = sum(1 for x, y in space if np.sqrt(x**2 + y**2) <= radius)
area_ratio = num_points_within_radius / sample_size
pi = 4 * area_ratio / radius**2
print(pi)
if __name__ == "__main__":
arguments = docopt.docopt(__doc__)
main(arguments)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment