-
-
Notifications
You must be signed in to change notification settings - Fork 46.8k
Add Monte Carlo estimation of PI #1712
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
Merged
cclauss
merged 5 commits into
TheAlgorithms:master
from
cschuerc:cschuerc/maths/pi_monte_carlo
Mar 14, 2020
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cdbd8a5
Add Monte Carlo estimation of PI
cschuerc eaff142
Add type annotations for Monte Carlo estimation of PI
cschuerc 67bcc8d
Compare the PI estimate to PI from the math lib
cschuerc 0a990ac
accuracy -> error
poyea 18932bc
Update pi_monte_carlo_estimation.py
poyea File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
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). | ||
""" | ||
x = random.random() | ||
y = random.random() | ||
|
||
return cls(x, y) | ||
poyea marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
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 simulation_index 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__": | ||
cclauss marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# 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 accuracy of {abs(my_pi - pi)}") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.