I am trying to estimate the value of pi using a monte carlo simulation. I need to use two unit circles that are a user input distance from the origin. This is what i have:
import random
import math
import sys
def main():
numDarts=int(sys.argv[1])
distance=float(sys.argv[2])
print(montePi(numDarts,distance))
def montePi(numDarts,distance):
width=2*(1-distance)
if distance>=1:
return(0)
inCircle=0
for i in range(numDarts):
x=(width*(random.random()))-width
y=(random.random())
d=(x-distance)**2+(y-0)**2
d2=(x-(distance*-1))**2+(y-0)**2
if d<=1 and d2>=-1:
inCircle=inCircle+1
pi=(inCircle/numDarts)*(width*2)
return pi
main()
This is what i should get-
when distance = 0, about 3.14 when distance = .5, about 1.288 i am getting about 1.6 and .6 respectively, why?
These are my instructions-
Write a program called mcintersection.py that uses the Monte Carlo method to estimate the area of this shape (and prints the result). Your program should take two command-line parameters: distance and numDarts. The distance parameter specifies how far away the circles are from the origin on the x-axis. So if distance is 0, then both circles are centered on the origin, and completely overlap. If distance is 0.5 then one circle is centered at (-0.5, 0) and the other at (0.5, 0). If distance is 1 or greater, then the circles do not overlap at all! In that last case, your program can simply output 0. The numDarts parameter should specify the number of random points to pick in the Monte Carlo process.
In this case, the rectangle should be 2 units tall (with the top at y = 1 and the bottom at y = -1). You could also safely make the rectangle 2 units wide, but this will generally be much bigger than necessary. Instead, you should figure out exactly how wide the shape is, based on the distance parameter. That way you can use as skinny a rectangle as possible.