Skip to content

Python3 monte carlo #148

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ Gathros
Jeremie Gillet (- Jie -)
Salim Khatib
Hitesh C
name
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably better if you put in your actual name :)

34 changes: 34 additions & 0 deletions chapters/monte_carlo/code/Python3/monte_carlo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import random
import math


def in_circle(x, y, r):
"""
return True if (x,y) is inside a circle with radius r
:param x: int or float, x position of a point
:param y: int or float, y position of a point
:param r: int or float, radius of circle
:return: True or false
"""
return x ** 2 + y ** 2 < r ** 2


def monte_carlo(n, r):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have moved away from using r as a free parameter in monte_carlo, so you can remove it here, and call in_circle(x, y, 1) instead of in_circle(x, y, r). Another, clean alternative is to change def in_circle(x, y, r): to def in_circle(x, y, r = 1): and then just use it as in_circle(x, y).

"""
calculate pi
:param n: int, number of points
:param r: radius of circle
:return: estimate of pi,
"""
points_in_circle = 0
for _dummy in range(n):
x = random.random()
y = random.random()
if in_circle(x, y, r):
points_in_circle += 1

pi_estimate = 4.0 * points_in_circle / (n * r ** 2)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then in this line you don't need r ** 2 anymore.

pi_erro = 100*(math.pi - pi_estimate)/math.pi
return pi_estimate, pi_erro

print(monte_carlo(10000000, 0.5))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The last thing is, it's best if you have a main() function that prints something like "The estimated value of pi is..." and "the Error is...". The error should be calculated in main() as well because it's not part of the algorithm.