# Monte Carlo method of computing pi
# Toss darts at a dart board (2x2, centered at (0,0)
# The ratio of the darts in the unit circle to all darts is pi/4
# (see problem 10, chapter 9 of book)
# ECS 10, May 11, 2009
# Matt Bishop
import random
import math
# Generate a landing position for a dart tossed at
# a 2x2 square with center at (0,0)
# returns: (x, y) co-ordinates of toss
def gentoss():
x = 2*random.random() - 1
y = 2*random.random() - 1
return x, y
# if x^2 + y^2 <= 1, they are in the unit circle
def inunitcircle(x, y):
return x ** 2 + y ** 2 <= 1
# function to read and vet user selection
# returns: n, the number of tosses
# NOTE: n must be positive; return -1 to quit
def getinput():
# loop until we get good input
while True:
try:
# get the input and check the type here
n = input("Enter the number of tosses: ")
n += 0;
except EOFError: # user wants to quit, so help her
n = -1
break
# oops! let error check below do the work
# so set v to something illegal (not 0-3)
except (SyntaxError, NameError, TypeError):
n = -1
# now check the value we read/were given
if n > 0:
break
# this is bad, so say so
print "You have to enter a positive number"
# it's non-negative to continue, -1 to quit
return n
# main routine: pull it all together
def main():
# get number of tosses
n = getinput()
if n > 0:
# number of darts in unit circle
# nothing thrown yet
h = 0
# now start throwing
for i in range(n):
# toss
x, y = gentoss()
# is it in the circle?
if inunitcircle(x, y):
h += 1
# done! see how well you did ...
print "approximation:", 4.0 * h / n, "actual", math.pi
main()