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
#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


Messages In This Thread
RE: Using Monte Carlo Simulation to Approximate pi - by scidam - May-16-2018, 02:33 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Simulation DaRTHYGT 2 2,774 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