One way to estimate the value of is to simulate a darts game. The darts player t
ID: 3785098 • Letter: O
Question
One way to estimate the value of is to simulate a darts game. The darts player throws at a circular board with a radius of 1 foot. The player's aim is such that the dart has a uniform chance of hitting the wall anywhere within a 1 foot by 1 foot square, with the center of the board the same as the center of the square.
In the estimation, the player throws n darts, hitting the board m times (i.e., m of the n throws hit the board. The estimate of is n/m
Write a class called Darts. It has 2 methods, called throw and pi. For example:
python 2.7.13
Explanation / Answer
import random
import math
class Darts:
def __init__(self):
self.m = 0;
self.n = 0;
def throw(self):
#increase total throws by 1
self.n = self.n + 1;
#increase m, if the throw got dart in the circle
#how
#find one random point (x,y) in circle
#and check if lie in square or not
x = random.random();
y = random.random();
while x*x + y*y > 1: #while we not find a point in circle
x = random.random();
y = random.random();
#got a point in circle
if( (x >= -0.5 and x <= 0.5) and
( y >= -0.5 and y <= 0.5 ) ): # in square
self.m = self.m + 1;
def pi(self):
#calculate value of pi
pi = (self.n*1.0)/self.m;
return pi;
d = Darts();
for i in range(1000):
d.throw();
print d.pi();
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.