Presentation is loading. Please wait.

Presentation is loading. Please wait.

If..else Use random numbers to compute an approximation of pi Simulation of a special game of darts Randomly place darts on the board pi can be computed.

Similar presentations


Presentation on theme: "If..else Use random numbers to compute an approximation of pi Simulation of a special game of darts Randomly place darts on the board pi can be computed."— Presentation transcript:

1 if..else Use random numbers to compute an approximation of pi Simulation of a special game of darts Randomly place darts on the board pi can be computed by keeping track of the number of darts that land on the board

2 Dart Board

3 Monte Carlo Simulation montePi.py import random import math def montePi(numDarts): inCircle = 0 for i in range(0, 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

4 Complete Program import random import math import turtle def showMontePi(numDarts): wn = turtle.Screen() dartT = turtle.Turtle() wn.setworldcoordinates(-2,-2,2,2) dartT.up() dartT.goto(-1,0) dartT.down() dartT.goto(1,0) dartT.up() dartT.goto(0,1) dartT.down() dartT.goto(0,-1) circle = 0 dartT.up() for i in range(numDarts): x = random.random() y = random.random() d = math.sqrt(x**2 + y**2) dartT.goto(x,y) if d <= 1: circle = circle + 1 dartT.color("blue") else: dartT.color("red”) dartT.dot() pi = circle/numDarts * 4 wn.exitonclick() return pi montePi=showMontePi(100) print(montePi)

5 Figure 2.14

6 Lab_0923 def drawCoordinate(): def drawDotPi(): import turtle import math import random t = turtle.Turtle() wn = turtle.getscreen() drawCoordinate() montePi=drawDotPi() print(montePi) Re-write montePi.py with two functions drawCoordinate() to draw the initial coordinates drawDotPi() to draw dart simulation Email to 2015fall91.100@gmail.com


Download ppt "If..else Use random numbers to compute an approximation of pi Simulation of a special game of darts Randomly place darts on the board pi can be computed."

Similar presentations


Ads by Google