Monte Carlo approximation of $\pi$

Question P2.5.10

The value of $\pi$ may be approximated by a Monte Carlo method. Consider 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.


Solution

To access solutions, please obtain an access code from Cambridge University Press at the Lecturer Resources page for my book (registration required) and then sign up to scipython.com providing this code.