Skip to content

Instantly share code, notes, and snippets.

@cdarringer
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdarringer/9729654339bef5a00296 to your computer and use it in GitHub Desktop.
Save cdarringer/9729654339bef5a00296 to your computer and use it in GitHub Desktop.
Random number pi calculator
"""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