-
-
Save shreve/27e7132f6e79271aa2d20050f5badcbf to your computer and use it in GitHub Desktop.
Computationally generate e
This file contains hidden or 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
# 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