Homework 3

Due: Feb 10 by 11:55 pm (London ON time)
Submit your Jupyter Notebook to OWL

Estimate \(\pi\) by throwing darts

Imagine a circle of radius (\(r\)) inscribed inside a square with side length \(2r\). Now imagine throwing a dart which lands at some random location within the square (imagine you are terribly random at throwing darts). Sometimes the dart will be inside the circle and sometimes it will not. If you count the number of darts that land inside the circle and divide that by the total number of darts, that ratio ought to equal \(\frac{\pi}{4}\).

As an exercise, implement this method of estimating \(\pi\). Write the program so that you can use any number of random darts \(n\). Start with 1000 darts and then try larger numbers. See how close you can get to the actual value of \(\pi\). Here are the first 100,000 digits of \(\pi\).

Write a function called estimatepi() that takes an integer n as input, and returns as output the estimated value of \(\pi\) using n throws of the dart.

Note that this algorithm is not a very efficient or fast way of getting the digits of \(\pi\), but it’s a fun programming exercise nevertheless and a way to get you coding.

Hint: you will need a function that generates random numbers.

In NumPy the np.random.rand() function samples from a uniform (pseudo)random distribution over the interval \((0,1)\).

Hint: to determine whether each point is inside or outside of the circle you can compute the distance between the point and the centre of the circle. If this distance is greater than the radius of the circle, it must be outside of the circle. Using the Pythagorean theorem you can easily show that the equation for the distance \(d\) between two points \((x_{1},y_{1})\) and \((x_{2},y_{2})\) is:

\[\begin{equation} d = \sqrt{(x_{2}-x_{1})^{2} + (y_{2}-y_{1})^{2}} \end{equation}\]

Your code should run like this, using your function estimatepi():

You might get slightly different values because of differences in the random number generator. That is OK.

print(f"estimate of pi using 1000 throws is: {estimatepi(1000):.5f}")
print(f"estimate of pi using 1,000,000 throws is: {estimatepi(1000000):.5f}")
print(f"estimate of pi using 10,000,000 throws is: {estimatepi(10000000):.5f}")
estimate of pi using 1000 throws is: 3.12800
estimate of pi using 1,000,000 throws is: 3.13950
estimate of pi using 10,000,000 throws is: 3.14030