Skip to content

Instantly share code, notes, and snippets.

@ric2b
Last active July 4, 2016 11:08
Show Gist options
  • Save ric2b/62c86e2f83cb1ef51c496a9c76062cec to your computer and use it in GitHub Desktop.
Save ric2b/62c86e2f83cb1ef51c496a9c76062cec to your computer and use it in GitHub Desktop.
Calculate the average distance between 2 random points inside a 1x1 square using a Monte Carlo simulation
from random import random # the random function yelds values between 0 and 1
def distance(x1,y1,x2,y2):
return ((x1-x2)**2+(y1-y2)**2)**(1/2)
def results(n):
for i in range(n):
yield distance(random(),random(),random(),random())
N = 10**6
print(sum(results(N))/N) # result is a very unintuitive ~0.521. An analitical solution is presented at youtube.com/watch?v=i4VqXRRXi68
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment