Python/maths/pi_monte_carlo_estimation.py
Caeden 4d0c830d2c
Add flake8 pluin flake8 bugbear to pre-commit (#7132)
* ci(pre-commit): Add ``flake8-builtins`` additional dependency to ``pre-commit`` (#7104)

* refactor: Fix ``flake8-builtins`` (#7104)

* fix(lru_cache): Fix naming conventions in docstrings (#7104)

* ci(pre-commit): Order additional dependencies alphabetically (#7104)

* fix(lfu_cache): Correct function name in docstring (#7104)

* Update strings/snake_case_to_camel_pascal_case.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update data_structures/stacks/next_greater_element.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update digital_image_processing/index_calculation.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update graphs/prim.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* Update hashes/djb2.py

Co-authored-by: Christian Clauss <cclauss@me.com>

* refactor: Rename `_builtin` to `builtin_` ( #7104)

* fix: Rename all instances (#7104)

* refactor: Update variable names (#7104)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* ci: Create ``tox.ini`` and ignore ``A003`` (#7123)

* revert: Remove function name changes (#7104)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Rename tox.ini to .flake8

* Update data_structures/heap/heap.py

Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>

* refactor: Rename `next_` to `next_item` (#7104)

* ci(pre-commit): Add `flake8` plugin `flake8-bugbear` (#7127)

* refactor: Follow `flake8-bugbear` plugin (#7127)

* fix: Correct `knapsack` code (#7127)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: Christian Clauss <cclauss@me.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Dhruv Manilawala <dhruvmanila@gmail.com>
2022-10-13 18:03:06 +02:00

68 lines
2.0 KiB
Python

import random
class Point:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def is_in_unit_circle(self) -> bool:
"""
True, if the point lies in the unit circle
False, otherwise
"""
return (self.x**2 + self.y**2) <= 1
@classmethod
def random_unit_square(cls):
"""
Generates a point randomly drawn from the unit square [0, 1) x [0, 1).
"""
return cls(x=random.random(), y=random.random())
def estimate_pi(number_of_simulations: int) -> float:
"""
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 is:
P[U in unit circle] = 1/4 PI
and therefore
PI = 4 * P[U in unit circle]
We can get an estimate of the probability P[U in unit circle].
See https://en.wikipedia.org/wiki/Empirical_probability by:
1. Draw a point uniformly from the unit square.
2. Repeat the first step n times and count the number of points in the unit
circle, which is called m.
3. An estimate of P[U in unit circle] is m/n
"""
if number_of_simulations < 1:
raise ValueError("At least one simulation is necessary to estimate PI.")
number_in_unit_circle = 0
for _ in range(number_of_simulations):
random_point = Point.random_unit_square()
if random_point.is_in_unit_circle():
number_in_unit_circle += 1
return 4 * number_in_unit_circle / number_of_simulations
if __name__ == "__main__":
# import doctest
# doctest.testmod()
from math import pi
prompt = "Please enter the desired number of Monte Carlo simulations: "
my_pi = estimate_pi(int(input(prompt).strip()))
print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")