COSC 235

Programming & Problem Solving


Project 5


Due October 16th (Monday) by 11:59PM

Overview

This project will give you practice with looping and if/else statements. You will use a technique called Monte Carlo simulation to approximate the number pi. The basically approach is that you throw a large number of "darts" at a dartboard, and seeing how many actually hit it.

To Do

Write a Python program (call it 'pi.py') by completing the following:

  1. Write a function monte(darts) that takes a number of darts as a parameter. The darts parameter represents how many darts you want to throw at an imaginary dart board.
  2. You should imagine the dartboard looking like the circle in the image below, and with the same dimensions.
  3. Assuming that every dart you "throw" lands inside the square, the fraction of the darts that land in the circle estimates the ratio between the area of the circle and the area of the square. We know that the area of the circle is C = pi*r2 = pi*12 = pi and the area of the square is S = 22 = 4. So the exact ratio is pi/4. With enough darts (say 'n', for example), the fraction (f) (between 0 and 1) that lands in the circle will approximate this ratio: f ≈ π/4, which means that π ≈ 4*f.
  4. Using this idea, write monte(darts) so that it approximates the value pi by repeatedly throwing random virtual darts that land at points with x and y coordinates in the range shown in the image below. Thus, both x and y should be a random number that land in the square. Count the number that land at points within distance 1 of the origin (think distance formula), and return this fraction.
  5. Create a main() function, and have it ask for the number of darts to throw.
  6. Make sure to call your main() function so that your program actually runs.
  7. Make sure to document your program by adding an author and date at the top, as well as adding several comments throughout the code.

Sample Run of the Program

Your program output will vary due to the use of random numbers, but your output should look similar to the following:


        Monte Carlo Simulator for Approximating PI

        How many darts do you want to throw: 1000

        The approximated value of pi is this_number_will_vary.
    

Submit

To submit, save your Python program in a file named 'pi.py', and submit it to Moodle by the due date.