Generates an estimate of the mathematical constant PI. See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle i
(number_of_simulations: int)
| 22 | |
| 23 | |
| 24 | def estimate_pi(number_of_simulations: int) -> float: |
| 25 | """ |
| 26 | Generates an estimate of the mathematical constant PI. |
| 27 | See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview |
| 28 | |
| 29 | The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from |
| 30 | the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: |
| 31 | |
| 32 | P[U in unit circle] = 1/4 PI |
| 33 | |
| 34 | and therefore |
| 35 | |
| 36 | PI = 4 * P[U in unit circle] |
| 37 | |
| 38 | We can get an estimate of the probability P[U in unit circle]. |
| 39 | See https://en.wikipedia.org/wiki/Empirical_probability by: |
| 40 | |
| 41 | 1. Draw a point uniformly from the unit square. |
| 42 | 2. Repeat the first step n times and count the number of points in the unit |
| 43 | circle, which is called m. |
| 44 | 3. An estimate of P[U in unit circle] is m/n |
| 45 | """ |
| 46 | if number_of_simulations < 1: |
| 47 | raise ValueError("At least one simulation is necessary to estimate PI.") |
| 48 | |
| 49 | number_in_unit_circle = 0 |
| 50 | for _ in range(number_of_simulations): |
| 51 | random_point = Point.random_unit_square() |
| 52 | |
| 53 | if random_point.is_in_unit_circle(): |
| 54 | number_in_unit_circle += 1 |
| 55 | |
| 56 | return 4 * number_in_unit_circle / number_of_simulations |
| 57 | |
| 58 | |
| 59 | if __name__ == "__main__": |
no test coverage detected