Created
February 3, 2018 20:41
-
-
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
This file contains hidden or 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
| # 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