Python Forum
Using Monte Carlo Simulation to Approximate pi
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Monte Carlo Simulation to Approximate pi
#1
Hi! I am a college student and self studying python by using the "how to think like a computer scientist-interactive version". In the lab session in this book, I need to approximate the value of pi by using Monte Carlo Simulation. I write the following codes but I am not sure if it is right. It did give me the result of pi, but the graph did not seem right. All the 10000 dots seem to concentrate at 4 corners (looks like 4 black squares), which concerns me. I read some "answers" to this question on the internet and nobody wrote similar codes like I did. Could anyone tell me if I have made a mistake? Thanks!

import turtle
import math
import random

fred = turtle.Turtle()
wn = turtle.Screen()
wn.setworldcoordinates(-2,-2,2,2)
wn.tracer(100)
fred.up()

numdarts = 10000
total=0
for i in range(numdarts):
    randx = random.random()
    randy = random.random()
    if randx>0.5 and randy>0.5:
        x=2*randx
        y=2*randy
    else:
        if randx>0.5 and randy<0.5:
            x=2*randx
            y=(-2)*randy
        else:
            if randx<0.5 and randy>0.5:
                x=(-2)*randx
                y=2*randy
            else:
                if randx<0.5 and randy<0.5:
                    x=(-2)*randx
                    y=(-2)*randy
                else:
                    x=0
                    y=0
    
    fred.goto(x,y)
    fred.stamp()
    dis=fred.distance(0,0)
    if dis<=2:
        total=total+1
    else:
        total=total+0
        
result=total/numdarts
pi=result*4
print("The value of pi is",pi) 
wn.exitonclick()
Reply
#2
Why did you use sophisticated nested if-statements?

import turtle
import math
import random
 
fred = turtle.Turtle()
wn = turtle.Screen()
wn.setworldcoordinates(-2, -2, 2, 2)
wn.tracer(100)
fred.up()
 
numdarts = 10000
total = 0
for i in range(numdarts):
    randx = random.random()
    randy = random.random()
    randx -= 0.5
    randy -= 0.5
    randx *= 2.0
    randy *= 2.0
    # now (randx, randy) is in [-2, 2]x[-2, 2]
    fred.goto(randx, randy)
    dis = fred.distance(0, 0)
    if dis <= 1: #unity circle
        fred.stamp()
        total = total + 1
    else:
        total = total + 0

result = total / numdarts
pi = result * 4
print("The value of pi is", pi) 
wn.exitonclick()
I got pi approx. 3.12, 3.17, so, 10000 isn't a sufficient number of simulations to get a good approximation of pi.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simulation DaRTHYGT 2 2,745 Jan-27-2020, 10:09 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020