Skip to content

Update pi monte carlo script to run tests with fixed seed. #12757

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions maths/pi_monte_carlo_estimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,20 @@ 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):
def random_unit_square(cls, ran: random.Random):
"""
Generates a point randomly drawn from the unit square [0, 1) x [0, 1).
Generates a point randomly drawn from the unit square [0, 1) x [0, 1),
using 'ran' random number generator
"""
return cls(x=random.random(), y=random.random())

return cls(x=ran.random(), y=ran.random())


def estimate_pi(number_of_simulations: int) -> float:
def estimate_pi(number_of_simulations: int, seed: int | None = None) -> float:
"""
Generates an estimate of the mathematical constant PI.
See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview
Expand All @@ -42,13 +45,24 @@ def estimate_pi(number_of_simulations: int) -> float:
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

'seed' provides seed for the number generator - if None, no seed is used.

>>> estimate_pi(100, 1)
3.2
>>> estimate_pi(1000, 11)
3.156
>>> estimate_pi(1000000, 111)
3.139892

"""
if number_of_simulations < 1:
raise ValueError("At least one simulation is necessary to estimate PI.")

number_in_unit_circle = 0
ran = random.Random(seed)
for _ in range(number_of_simulations):
random_point = Point.random_unit_square()
random_point = Point.random_unit_square(ran)

if random_point.is_in_unit_circle():
number_in_unit_circle += 1
Expand All @@ -57,11 +71,6 @@ def estimate_pi(number_of_simulations: int) -> float:


if __name__ == "__main__":
# import doctest

# doctest.testmod()
from math import pi
import doctest

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)}")
doctest.testmod()