analytics

Tuesday, October 18, 2011

A Monte Carlo for approximating e

I noticed experimentally that if you pick a random series of consecutive floating point numbers between 0 and 1 and stop when you've exceeded a sum of 1.0, you've picked on average e numbers. It always takes at least 2 numbers to add to more than 1 because each less than 1, but it could take an infinitely long time to exceed a sum of 1.0 because a floating point number can be infinitely close to 0. But in practice on average it takes a little less than three numbers, so close to e that I'm kind of assuming that it is e though I'd like to prove it.
For instance, say I picked randomly:
.248727...
.671823...
These add to only .92...
so I pick another:
.31333
Ok that exceeded 1.0 when you add all 3 so 3 goes on a list. Then I do this, say 100,000 times and average the number of tries and it came out to in one case:
2.71859
which is very close to the correct value of e:
2.71828...

I've heard many facts about e but I've never heard this particular simple one so I thought I'd post it. Here is some python source code:

import random
def trial():
    sum = 0
    counter = 0
    while sum < 1:
        sum+=random.random()
        counter+=1
    return counter
def main():
    t = 0.0
    for i in range(0, 100000):
        t+=trial()
    print t/100000
main()

No comments:

Post a Comment