Created
August 10, 2014 14:16
-
-
Save jmateus/18f453b0e613e1667030 to your computer and use it in GitHub Desktop.
Monte Carlo method for finding pi
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
from __future__ import division | |
import random | |
import sys | |
import math | |
def main(): | |
# The first command line argument defines the number of iterations | |
# of the algorithm. The default value is 400. | |
if len(sys.argv) > 1: | |
num_iters = int(sys.argv[1]) | |
else: | |
num_iters = 400 | |
# How many of the randomly generated points are inside the circle. | |
points_in_circle = 0 | |
# Generate num_iters points (between (0,0) and (1,1)) and check if | |
# they are inside the circle. | |
for i in xrange(num_iters): | |
x, y = random.random(), random.random() | |
if math.pow(x, 2) + math.pow(y, 2) <= 1: | |
points_in_circle += 1 | |
# Use the formula for the area of a circle to find pi. | |
pi = (points_in_circle / num_iters) * 4 | |
print 'Pi is', pi | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment