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..041839dc2 --- /dev/null +++ b/contents/monte_carlo_integration/code/python/monte_carlo.py @@ -0,0 +1,35 @@ +import math +import random + + +def in_circle(x, y, radius = 1): + """Return True if the point is in the circle and False otherwise.""" + return (x*x + y*y) < radius*radius + +def monte_carlo(n_samples, radius = 1): + """Return the estimate of pi using the monte carlo algorithm.""" + in_circle_count = 0 + for i in range(n_samples): + + # Sample x, y from the uniform distribution + x = random.uniform(0, radius) + y = random.uniform(0, radius) + + # Count the number of points inside the circle + if(in_circle(x, y, radius)): + in_circle_count += 1 + + # Since we've generated points in upper left quadrant ([0,radius], [0, radius]) + # We need to multiply the number of points by 4 + pi_estimate = 4 * in_circle_count / (n_samples) + + return pi_estimate + +if __name__ == '__main__': + + pi_estimate = monte_carlo(100000) + percent_error = 100*abs(math.pi - pi_estimate)/math.pi + + print("The estimate of pi is: {:.3f}".format(pi_estimate)) + print("The percent error is: {:.3f}".format(percent_error)) + diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index 84a158e92..c9613f577 100644 --- a/contents/monte_carlo_integration/monte_carlo_integration.md +++ b/contents/monte_carlo_integration/monte_carlo_integration.md @@ -58,7 +58,9 @@ each point is tested to see whether it's in the circle or not: {% sample lang="java" %} [import:13-15, lang:"java"](code/java/MonteCarlo.java) {% sample lang="swift" %} -[import:15-17 lang:"swift"](code/swift/monte_carlo.swift) +[import:15-17, lang:"swift"](code/swift/monte_carlo.swift) +{% sample lang="py" %} +[import:5-7, lang:"python"](code/python/monte_carlo.py) {% 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="py" %} +[import, lang:"python"](code/python/monte_carlo.py) {% endmethod %}