Skip to content

Add Python code to Monte Carlo Integration #294

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
36 changes: 36 additions & 0 deletions contents/monte_carlo_integration/code/python/monte_carlo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# submitted by hybrideagle
from random import random
from math import pi


def in_circle(x_pos, y_pos):
radius = 1
# Compute euclidian distance from origin
return (x_pos * x_pos + y_pos * y_pos) < (radius * radius)


def monte_carlo(n):
"""
Computes PI using the monte carlo method using `n` points
"""
pi_count = 0

for i in range(n):
x = random()
y = random()
if in_circle(x, y):
pi_count += 1

# This is using a quarter of the unit sphere in a 1x1 box.
# The formula is pi = (boxLength^2 / radius^2) * (piCount / n), but we
# are only using the upper quadrant and the unit circle, so we can use
# 4*piCount/n instead
# piEstimate = 4*piCount/n
pi_estimate = 4 * pi_count / n
print('Pi is {0:} ({1:.4f}% error)'.format(
pi_estimate, (pi - pi_estimate) / pi * 100))


# If this file was run directly
if __name__ == "__main__":
monte_carlo(100000)
4 changes: 4 additions & 0 deletions contents/monte_carlo_integration/monte_carlo_integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ each point is tested to see whether it's in the circle or not:
[import:13-15, lang:"java"](code/java/MonteCarlo.java)
{% sample lang="swift" %}
[import:15-17 lang:"swift"](code/swift/monte_carlo.swift)
{% sample lang="python" %}
[import:6-10 lang:"python"](code/python/monte_carlo.python)
{% endmethod %}

If it's in the circle, we increase an internal count by one, and in the end,
Expand Down Expand Up @@ -112,6 +114,8 @@ Feel free to submit your version via pull request, and thanks for reading!
[import, lang:"java"](code/java/MonteCarlo.java)
{% sample lang="swift" %}
[import, lang:"swift"](code/swift/monte_carlo.swift)
{% sample lang="python" %}
[import, lang:"python"](code/python/monte_carlo.python)
{% endmethod %}


Expand Down