MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / pi_estimator

Function pi_estimator

maths/monte_carlo.py:11–39  ·  view source on GitHub ↗

An implementation of the Monte Carlo method used to find pi. 1. Draw a 2x2 square centred at (0,0). 2. Inscribe a circle within the square. 3. For each iteration, place a dot anywhere in the square. a. Record the number of dots within the circle. 4. After all the dots are

(iterations: int)

Source from the content-addressed store, hash-verified

9
10
11def pi_estimator(iterations: int) -> None:
12 """
13 An implementation of the Monte Carlo method used to find pi.
14 1. Draw a 2x2 square centred at (0,0).
15 2. Inscribe a circle within the square.
16 3. For each iteration, place a dot anywhere in the square.
17 a. Record the number of dots within the circle.
18 4. After all the dots are placed, divide the dots in the circle by the total.
19 5. Multiply this value by 4 to get your estimate of pi.
20 6. Print the estimated and numpy value of pi
21 """
22
23 # A local function to see if a dot lands in the circle.
24 def is_in_circle(x: float, y: float) -> bool:
25 distance_from_centre = sqrt((x**2) + (y**2))
26 # Our circle has a radius of 1, so a distance
27 # greater than 1 would land outside the circle.
28 return distance_from_centre <= 1
29
30 # The proportion of guesses that landed in the circle
31 proportion = mean(
32 int(is_in_circle(uniform(-1.0, 1.0), uniform(-1.0, 1.0)))
33 for _ in range(iterations)
34 )
35 # The ratio of the area for circle to square is pi/4.
36 pi_estimate = proportion * 4
37 print(f"The estimated value of pi is {pi_estimate}")
38 print(f"The numpy value of pi is {pi}")
39 print(f"The total error is {abs(pi - pi_estimate)}")
40
41
42def area_under_curve_estimator(

Callers

nothing calls this directly

Calls 2

meanFunction · 0.85
is_in_circleFunction · 0.85

Tested by

no test coverage detected