e from random sums

algorythms
twitter
Author

David Dobrinskiy

Published

May 31, 2021

select numbers between 0 and 1 randomly until sum is > 1

The expected # of selections needed is equal to e
# setup imports
import math
from typing import Tuple

import numpy as np
import pandas as pd
from tqdm.notebook import trange
def run_experiment() -> Tuple[float, int]:
    s = 0
    n = 0

    while s <= 1:
        n += 1
        s += np.random.uniform(0, 1)

    return s, n


logs = [run_experiment() for _ in trange(2_000_000)]

df = pd.DataFrame(logs, columns=["sum", "nums_to_one"])
df.head()
sum nums_to_one
0 1.160454 2
1 1.099141 2
2 1.171709 3
3 1.664728 3
4 1.291741 2
euler's number: 2.718282
avg num to one: 2.717664
     avg sum*2: 2.718284
df.describe()
sum nums_to_one
count 2.000000e+06 2.000000e+06
mean 1.359142e+00 2.717664e+00
std 2.425132e-01 8.745580e-01
min 1.000000e+00 2.000000e+00
25% 1.152672e+00 2.000000e+00
50% 1.325424e+00 2.000000e+00
75% 1.538078e+00 3.000000e+00
max 1.999527e+00 9.000000e+00