Learning Scientific Programming with Python (2nd edition)

P2.5.10: Monte Carlo approximation of $\pi$

Question P2.5.10

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.