Skip to content

Instantly share code, notes, and snippets.

@fela
Last active August 16, 2016 16:12
Show Gist options
  • Save fela/11ecc0180c94c7d100dbc54191d083a8 to your computer and use it in GitHub Desktop.
Save fela/11ecc0180c94c7d100dbc54191d083a8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import sys
from random import random
def single_trial():
"""
Generate a random 2 dimensional point between (0, 0) and (1, 1)
and returns weather the distance to the origin is less than 1
|^^-- , + (1, 1)
| \_ False
| \
| True \
| |
|______________|
(0, 0)
"""
x, y = random(), random()
return x**2 + y**2 < 1
def pi_approximation(n_trials):
# run n trials
count = sum(single_trial() for _ in range(n_trials))
# count / n_trials ~= pi/4 => pi ~= 4*count/n_trials
return 4.0 * count / n_trials
def main()
if len(sys.argv) < 2: # check if a command line argument is passed
# if not, use the default
n_trials = 1000000
print("Using the default of {} trials".format(n_trials))
else:
# get the command line argument
n_trials = int(sys.argv[1])
print(pi_approximation(n_trials))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment