# pi_montecarlo.py -- timdoug[.com|@gmail.com]* -- 2008-07-17 # a simple Monte Carlo simulation to calculate pi # not fast in the least bit, but shows the concept clearly (I hope!) import math import random import Tkinter master = Tkinter.Tk() w = Tkinter.Canvas(master, width = 600, height = 600) w.pack() w.create_rectangle(4, 4, 600, 600) w.create_oval(4, 4, 600, 600) in_circle = 0; in_square = 5000; for i in range(0, in_square): x, y = random.randint(4, 600), random.randint(4, 600) w.create_rectangle(x, y, x+1, y+1) if math.sqrt((x-298)**2 + (y-298)**2) < 298: in_circle += 1; print "points in circle:", in_circle print "points in square:", in_square print "pi approximation:", float(in_circle * 4)/in_square master.mainloop()