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