diff --git a/contents/monte_carlo_integration/code/python/monte_carlo.py b/contents/monte_carlo_integration/code/python/monte_carlo.py new file mode 100644 index 000000000..1ec73c33d --- /dev/null +++ b/contents/monte_carlo_integration/code/python/monte_carlo.py @@ -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) diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index 84a158e92..7c5c5edaa 100644 --- a/contents/monte_carlo_integration/monte_carlo_integration.md +++ b/contents/monte_carlo_integration/monte_carlo_integration.md @@ -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, @@ -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 %}