import math import random def calculate_pi(num_samples): in_circle = 0 for i in range(num_samples): x = random.uniform(0,1) y = random.uniform(0,1) # figure out the distance dist = math.sqrt(x*x + y*y) # see if it's inside the circle if dist <= 1: in_circle += 1 # same as in_circle = in_circle + 1 # calculate pi based on how many are in the circle return 4 * in_circle/float(num_samples)