Skip to content

Instantly share code, notes, and snippets.

@jrjames83
Created February 3, 2018 20:41
Show Gist options
  • Save jrjames83/9baae0d9430246f27586b4e48c75ca96 to your computer and use it in GitHub Desktop.
Save jrjames83/9baae0d9430246f27586b4e48c75ca96 to your computer and use it in GitHub Desktop.
Simulating the area of a circle with radius R by throwing darts at a square of length 2*r
# Finding the area of a circle through simulation?
import math
import random
def dart_throw_simulator(radius, runs):
hits = 0
for run in range(runs):
rand_x = random.uniform(-2,2)
rand_y = random.uniform(-2,2)
c_squared = (rand_x ** 2) + (rand_y ** 2)
outcome = math.sqrt(c_squared)
if outcome < radius:
hits += 1
hit_ratio = hits / runs
total_area_square = (2*radius)**2
return hit_ratio * total_area_square
%time assert(dart_throw_simulator(2, 100000) > 12 and dart_throw_simulator(2, 1000000) < 13)
>>CPU times: user 1.43 s, sys: 34.3 ms, total: 1.47 s
>>Wall time: 1.53 s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment