Last active
August 29, 2015 14:17
-
-
Save cdarringer/9729654339bef5a00296 to your computer and use it in GitHub Desktop.
Random number pi calculator
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
"""Calculate pi using a random number generator | |
Calculate pi with progressively increasing accuracy using a random | |
number generator and some basic properties about circles and area. | |
Happy "pi day"! | |
author: Chris Darringer | |
""" | |
import random | |
import math | |
RADIUS = 100000 | |
MAX_TEST_COUNT = 3000000 | |
UPDATE_PERIOD = 100000; | |
def main(): | |
random.seed() | |
inCount = 0 | |
for i in range(1, MAX_TEST_COUNT + 1): | |
x = random.randint(-1 * RADIUS, RADIUS) | |
y = random.randint(-1 * RADIUS, RADIUS) | |
distanceFromCenter = math.sqrt(x**2 + y**2) | |
if (distanceFromCenter <= RADIUS): | |
inCount += 1 | |
if ((i % UPDATE_PERIOD) == 0): | |
print 'After', i, 'tests, pi is', str(4 * (float(inCount) / i)) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment