import random # MC integration 1 def compute_pi1(N): step = 0 sum = 0 while step < N: x = random.random() y = random.random() if x*x + y*y < 1.0: sum += 1 step += 1 return (4.0 * sum) / N # MC integration 2 def compute_pi2(N): step = 0 sum = 0.0 while step < N: x = random.random() sum += (1.0 - x*x) ** 0.5 step += 1 return 4.0 * sum / N # Numerical integration 3 def compute_pi3(N): x = 0.0 sum = 0.0 while x < 1.0: sum += (1.0 - x*x) ** 0.5 x += 1.0/N return 4.0 * sum / N