Created
December 20, 2016 22:30
-
-
Save plegner/56c75a36a2aa1a73ae79f60ec05346fe to your computer and use it in GitHub Desktop.
How far away is the closest alien civilisation in our galaxy?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import random | |
# Pick a random location that is uniformly distributed in a disk of radius r. | |
def random_point(r): | |
r = random.uniform(0, 1) | |
t = random.uniform(0, 2 * math.pi) | |
x = math.sqrt(r) * math.cos(t) * r | |
y = math.sqrt(r) * math.sin(t) * r | |
return [x, y] | |
# Find the distance between two points. | |
def distance(a, b): | |
dx = a[0] - b[0] | |
dy = a[1] - b[1] | |
return math.sqrt(dx * dx + dy * dy) | |
# Find the average shotest distance between n points in a disk of radius r. | |
# This function in O(n^2), but there are more efficient alternatives! | |
def average_distance(n, r): | |
points = [random_point(r) for _ in range(n)] | |
distances = [min([distance(p, q) for q in points if q != p]) for p in points] | |
return reduce(lambda x, y: x + y, distances) / len(distances) | |
NUMBER_OF_CIVILISATIONS = 1000 | |
RADIUS_OF_GALAXY = 70 # thousand light years | |
print(average_distance(NUMBER_OF_CIVILISATIONS, RADIUS_OF_GALAXY)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment