-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom_ge_one.py
44 lines (32 loc) · 1.04 KB
/
random_ge_one.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
"""random_ge_one.py
Add up uniformly distributed random numbers between zero and one, counting how
many you need to have your sum >= 1. An interesting thing happens if you do
this n times and take the average (for large values of n)...
See explanation here, for spoilers:
http://www.mostlymaths.net/2010/08/and-e-appears-from-nowhere.html
GE, 2/9/11
"""
# Used for reading command line arguments
import sys
# Gives (approximately) uniformly distributed random real numbers in [0, 1]
from random import random
# Adds random numbers until sum >= 1; returns the number of iterations needed
def single_run():
total = iters = 0
while total < 1:
total += random()
iters += 1
return iters
# Takes the average of n "single runs"
def n_runs_average(n):
total = 0.0
for i in range(n):
total += single_run()
return total / n
# Main execution
if __name__ == "__main__":
try:
print(n_runs_average(int(sys.argv[1])))
except (IndexError, ValueError):
print(n_runs_average(1000))