import random def random_around_zero(r): """ Return a random float in the range [-r, r]""" width = 2*r return random.random()*width - r def random_throw(r): """Return a random point in the square [(-r,r),(r,r),(r,-r),(-r,-r)]""" x = random_around_zero(r) y = random_around_zero(r) return x, y def in_circle(r, x, y): """Return True if (x,y) is in a circle with radius r centered at 0. Otherwise False.""" d = (x*x + y*y)**0.5 return d <= r def number_in_circle(n_total, r=0.5): """Test n_total random points (x,y) in a square with sides 2r and return the number of points that are inside a circle of radius r.""" n_circle = 0 for i in xrange(n_total): x,y = random_throw(r) if in_circle(r, x, y): n_circle += 1 return n_circle def number_in_circle_monolithic(n_total, r=0.5): n_circle = 0 for i in xrange(n_total): x = 2*r*random.random() - r y = 2*r*random.random() - r d = (x*x + y*y)**0.5 if d <= r: n_circle += 1 return n_circle def main(): for i in range(8): n_total = 10**i n_circle = number_in_circle(n_total) pi = 4.0*n_circle/n_total print '1x10^' + str(i) + ':', pi if __name__ == '__main__': main()