Skip to content

Instantly share code, notes, and snippets.

@shreve
Last active December 18, 2021 18:48
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 shreve/27e7132f6e79271aa2d20050f5badcbf to your computer and use it in GitHub Desktop.
Save shreve/27e7132f6e79271aa2d20050f5badcbf to your computer and use it in GitHub Desktop.
Computationally generate e
# Code sample of the following tweet:
# https://twitter.com/fermatslibrary/status/1449027186267197463
import random
import math
def compute_average(d):
return sum([num * count for (num, count) in d.items()]) / sum(d.values())
def sim():
counts = {}
iters = 0
while True:
iters += 1
_sum = 0
count = 0
while _sum < 1:
count += 1
_sum += random.uniform(0, 1)
if count not in counts:
counts[count] = 0
counts[count] += 1
avg = compute_average(counts)
diff = math.e - avg
if abs(diff) < 1e-7:
break
print(f"Average: {avg}\t Diff: {diff} Iters: {iters}")
if __name__ == "__main__":
sim()
# Sample Output:
# Average: 2.7182818352059925 Diff: -6.746947445179785e-09 Iters: 42720
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment