CS 100

Logo

Scientific Computing

Activity 9 - Pi: Monte Carlo approximation

  1. Create a file named monteCarlo.py, and at the top import three libraries: math, random, and turtle. Add to this file.
def montePi(numDarts):
    inCircle = 0       
    for i in range(numDarts):
        x = random.random()
        y = random.random()
        d = math.sqrt(x**2 + y**2)   
        if d <= 1:
            inCircle = inCircle + 1
    pi = inCircle/numDarts * 4
    return pi
  1. Call the montePi function with numDart at 100 and print the result. You should get a number close to Pi. Run your program for several times with the same number of darts, numDart=100. Do you get the same approximation for Pi? Why? Write your answer in comments.

  2. Add inside your monteCarlo.py the following function and call it with 50 darts.

def showMontePi(numDarts):
    wn = turtle.Screen()
    wn.bgcolor("light green")
    wn.setworldcoordinates(-2,-2,2,2)

    drawingT = turtle.Turtle()

    drawingT.up()
    drawingT.goto(-1,0)
    drawingT.down()
    drawingT.goto(1,0)

    drawingT.up()
    drawingT.goto(0,1)
    drawingT.down()
    drawingT.goto(0,-1)

    circle = 0
    drawingT.up()
    turtle.tracer(2,1) # tell turtle module to update display quickly
    
    for i in range(numDarts):
        x = random.random()
        y = random.random()
        d = math.sqrt(x**2 + y**2)
        drawingT.goto(x,y)
        if d <= 1:
            circle = circle + 1
            drawingT.color("blue")
        else:
            drawingT.color("red")            
        drawingT.dot()
        
    pi = circle/numDarts * 4
    return pi
  1. Comment out the previous function call and try it with 100 darts.

  2. Add a line in your showMontePi function that will change the color of the background. (See pg. 75 or the online Python documentation if you do not remember how to do this.)

  3. Explain in comments what the following command from showMontePi accomplishes: wn.setworldcoordinates(-2,-2,2,2)

  4. Complete problem 2.40 on pg 79.

If you finish early

  1. Compare the Monte Carlo method to the other Pi approximation methods. Which one is more accurate for large values of sides/pairs/terms/darts?

  2. Create a new function monteCircle with all the same code as showMontePi. Modify monteCircle so that 1) it only draws darts that are inside the circle, and 2) darts are mirrored so that they appear on all four quadrants of the cartesian plane. When finished, call your function with a large number of darts to ‘fill in’ a circle.

How to submit

Submit your monteCarlo.py file to Moodle.