Search code examples
pythonmontecarlopiapproximation

python, turtles, pi and monte carlo


I'm trying to approximate pi using a monte carlo with turtles in python. The code is running well but I've got a problem, my "approximations" are all terribly wrong. I' always get values smaller than 1 so??? My code is here below

import turtle
import math
import random

fred = turtle.Turtle()
fred.speed(0)
fred.up()

wn = turtle.Screen()
wn.setworldcoordinates(-1,-1,1,1)

numdarts = int(input("How many darts will you throw"))
for i in range(numdarts):
x = random.random()
y = random.random()
numIncircle = 0

if i == 0 or i == 1:
    fred.up()
    fred.goto(x, y)


    if fred.distance(0, 0) <= 1:
        numIncircle += 1
        fred.color("Indianred")
        fred.stamp()
        fred.up()
    else:
        numIncircle += 0
        fred.color("cyan")
        fred.stamp()
        fred.up()


else:
    fred.goto(x, y)

    if fred.distance(0, 0) <= 1:
        numIncircle += 1
        fred.color("Indianred")
        fred.stamp()
        fred.up()
    else:
        numIncircle += 0
        fred.color("cyan")
        fred.stamp()
        fred.up()

piapproximation = float(float(numIncircle) / float(numdarts)) * 4

print piapproximation

wn.exitonclick()

Solution

  • You're setting numIncircle = 0 inside your for loop, effectively losing count each time.

    Occasionally it'll count the last one, so the approximation will be 1 / number of darts * 4. This will happen with frequency pi / 4 ≈ 0.78539816339.

    Here is my suggestion:

    import turtle
    import math
    import random
    
    fred = turtle.Turtle()
    fred.speed(0)
    fred.up()
    
    wn = turtle.Screen()
    wn.setworldcoordinates(-1,-1,1,1)
    
    numdarts = int(input("How many darts will you throw"))
    
    // this MUST come before the for loop
    numIncircle = 0
    
    for i in range(numdarts):
    x = random.random() * 2 - 1
    y = random.random() * 2 - 1
    
    if i == 0 or i == 1:
        fred.up()
        fred.goto(x, y)
    
        if fred.distance(0, 0) <= 1:
            numIncircle += 1
            fred.color("Indianred")
            fred.stamp()
            fred.up()
        else:
            numIncircle += 0
            fred.color("cyan")
            fred.stamp()
            fred.up()
    else:
        fred.goto(x, y)
    
        if fred.distance(0, 0) <= 1:
            numIncircle += 1
            fred.color("Indianred")
            fred.stamp()
            fred.up()
        else:
            numIncircle += 0
            fred.color("cyan")
            fred.stamp()
            fred.up()
    
    piapproximation = float(float(numIncircle) / float(numdarts)) * 4
    
    print piapproximation
    
    wn.exitonclick()