In: Computer Science
Python
Problem 4. Estimate pi version 2: write a program that will quickly estimate pi to a precision of 1e-4 using a monte carlo approach. Your program should employ a loop where each iteration produces a new x,y pair. One will then determine whether the x,y pair lies inside or outside the circle. (see below) Since all the points will land within the square shown above but only a fraction will land within the circle, we can estimate pi by relating the area of the quarter circle shown above to the area of the square. As we randomly choose points, we can determine if they fall within the circle or not and form a ratio as shown below: AreaQtrcircle / AreaSqaure = πr 2 / 4r 2 = π / 4 = Points in Circle / All Points, π ≅ 4* Points in Circle / All Points.
Your loop should continue until the absolute value of the difference between the current estimate and the previous estimate is less than 1e-4. The program should output the estimate of pi and the number of iterations (points) needed to reach the desired level of precision. Run your program several times to see if the number of points changes. Note any observations in the comments.
import random prevEstimate = None currentEstimate = None iterations = 0 pointsInCircle = 0 pointsInSquare = 0 while True: (x, y) = (random.random(), random.random()) iterations += 1 if x*x + y*y <= 1: pointsInCircle += 1 pointsInSquare += 1 # min 100 iterations should be done. currentEstimate = 4.0 * pointsInCircle / pointsInSquare if prevEstimate is None or iterations <= 100: prevEstimate = currentEstimate elif abs(prevEstimate - currentEstimate) < 10**-4: break else: prevEstimate = currentEstimate print('Value:', currentEstimate) print('Iterations', iterations)
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.