Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Monte Carlo Estimation of PI in Python
import random as r
import math as m
# Number of darts that land inside.
inside = 0
# Total number of darts to throw.
total = 1000
# Iterate for the number of darts.
for i in range(0, total):
# Generate random x, y in [0, 1].
x2 = r.random()**2
y2 = r.random()**2
# Increment if inside unit circle.
if m.sqrt(x2 + y2) < 1.0:
inside += 1
# inside / total = pi / 4
pi = (float(inside) / total) * 4
# It works!
print(pi)
@dandrewmyers

This comment has been minimized.

Copy link

commented Apr 5, 2018

Made a version of your Monte Carlo pi code with a plot. Here is link:
https://github.com/dandrewmyers/numerical/blob/master/mc_pi.py

@laffra

This comment has been minimized.

Copy link

commented Mar 13, 2019

I made a visualization for this code on PyAlgoViz.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.