Skip to content

Instantly share code, notes, and snippets.

@jkbnerad
Created March 14, 2016 19:48
Show Gist options
  • Save jkbnerad/b4971241eff6cfc74347 to your computer and use it in GitHub Desktop.
Save jkbnerad/b4971241eff6cfc74347 to your computer and use it in GitHub Desktop.
'''
Buffon's Needle Experiment
Inspired by Werner Krauth, http://www.lps.ens.fr/~krauth/index.php/Main_Page
'''
import random
import math
def buffon_needle(throws, needle_length, cracks_distance):
print('Buffon\'s Needle Experiment')
print('needle = ' + str(needle_length) + ', crack = ' + str(cracks_distance))
print('\n')
print('Hits Estimate of PI')
if needle_length > cracks_distance:
raise Exception('The distance of cracks must be greater or equal than the length of the needle.')
hits = 0
for i in range(throws):
x_center = random.uniform(0, cracks_distance / 2) # random center x
tau = 2 # τ, orientation
while tau > 1:
dx = random.uniform(0, 1)
dy = random.uniform(0, 1)
tau = math.sqrt(dx ** 2 + dy ** 2)
if tau <= 1:
xtip = x_center - (needle_length / 2) * dx / tau
if xtip < 0: # intersect
hits += 1
# pi = 2*l*n / t*h
c = 2 * needle_length * throws
d = cracks_distance * hits
print(str(hits) + ' ' + str(c / d))
hits = buffon_needle(throws=5000, needle_length=1, cracks_distance=2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment