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 1 commit
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
35 changes: 35 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,35 @@
# submitted by hybrideagle
from random import random
from math import pi


def inCircle(xPos, yPos):
Copy link
Contributor

Choose a reason for hiding this comment

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

Functions and variables are usually named using snake_case rather than camelCase in Python. For example,. this line should rather be:

def in_circle(x_pos, y_pos):

This goes for everything in this file.

radius = 1
# Compute euclidian distance from origin
return (xPos * xPos + yPos * yPos) < (radius * radius)


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

for i in range(n):
pointX = random()
pointY = random()
if inCircle(pointX, pointY):
piCount += 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
piEstimate = 4 * piCount / n
print('Pi is {0:} ({1:.4f}% error)'.format(
piEstimate, (pi - piEstimate) / pi * 100))


if __name__ == "__main__":
monteCarlo(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