P2.5.10Monte Carlo approximation of \(\pi\)
The value of \(\pi\) may be approximated by a Monte Carlo method. Consider the region of the \(xy\)-plane bounded by \(0 \le x \le 1\) and \(0 \le y \le 1\). By selecting a large number of random points within this region and counting the proportion of them lying beneath the function \(y=\sqrt{1-x^2}\) describing a quarter-circle, one can estimate \(\pi/4\), this being the area bounded by the axes and \(y(x)\). Write a program to estimate the value of \(\pi\) by this method.
Hint: Use Python's random module: The method random.random() generates a (pseudo-)random number between 0. and 1. See Section 4.5.1 of the book for more information.
Show solution
Note that this Monte Carlo method converges extremely slowly (to get each new decimal place we have to increase the number of random points by a factor of 10):
import math
import random
N = 10000
def f(x):
return math.sqrt(1.-x**2)
pi = 0.
for i in range(N):
xi, yi = random.random(), random.random()
if yi <= f(xi):
pi += 1.
pi *= 4 / N
print('pi is approximately {:.4f}'.format(pi))
The output is:
pi is approximately 3.1432